对 带头结点的单链表 的操作
//帶頭結點的單鏈表
#include<iostream>
using namespace std;
typedef struct student
{
?????? int data;
?????? struct student *next;
}node;
node * creat()????????????????????????? //創建單鏈表
{
?????? node *head,*p,*s;
?????? int x,cycle=1;
?????? head=(node *)malloc(sizeof(node));
?????? p=head;
?
?????? while(cycle)
?????? {
?
????????????? cout<<"請輸入一直不為0的數,輸入0則結束"<<endl;
????????????? cin>>x;
????????????? if(x!=0)
????????????? {
???????????????????? s=(node *)malloc(sizeof(node));
???????????????????? s->data=x;
???????????????????? p->next=s;
???????????????????? p=s;
????????????? }
????????????? else cycle=0;
?
?????? }
?????? p->next=NULL;
?????? return head;
}
int listLength(node *head)??????????????????????? //單鏈表的測長
{
?????? int i=0;
?????? node *p=head;
?????? p=head;
????????????? do
????????????? {
???????????????????? p=p->next;
????????????? ? i++;
?
????????????? }while(p->next!=NULL);
????????????? return i;
}
void printList(node *head)?????????????????????? //打印單鏈表
{
?????? node *p=head->next;
?????? int len=listLength(head);
?????? for(int i=0;i<len;i++)
?????? {
????????????? cout<<p->data<<endl;
????????????? p=p->next;
?????? }
}
node * deleteNode(node *head,int e)????????????????????????? //刪除單鏈表的結點
{
?????? node *p1,*p2;
?????? p1=head->next;
?????? while(p1->data!=e && p1->next!=NULL)
?????? {
????????????? p2=p1;
????????????? p1=p1->next;
?????? }
?????? if(e==p1->data)
?????? {
????????????? if(p1==head->next)
????????????? {
???????????????????? head->next=p1->next;
???????????????????? free(p1);
????????????? }
????????????? else
????????????? {
???????????????????? p2->next=p1->next;
???????????????????? free(p1);
????????????? }
?
?????? }
?????? else
????????????? cout<<"未找到結點的數據域值為:"<<e<<"的結點"<<endl;
?????? return head;
?
}
node * insert(node *head,int e)?? //鏈表插入一個結點
{
?????? node *p1,*p2,*s;
?????? p1=head->next;
?????? s=(node *)malloc(sizeof(node));
?????? s->data=e;
?????? while(s->data > p1->data && p1->next!=NULL)
?????? {
????????????? p2=p1;
????????????? p1=p1->next;
?????? }
?????? if(s->data < p1->data)
?????? {
????????????? if(p1==head->next)
????????????? {
???????????????????? s->next=p1;
???????????????????? head->next=s;
????????????? }
????????????? else
????????????? {
???????????????????? s->next=p1;
???????????????????? p2->next=s;
????????????? }
?????? }
?????? else
????????????? p1->next=s;
?????? s->next=NULL;
?????? return head;
}
int main()
{
?????? node *head;
?????? head=creat();
?????? printList(head);
?????? head=insert(head,3);
??? printList(head);
?????? return 0;
}
轉載于:https://www.cnblogs.com/this-543273659/archive/2011/08/03/2126157.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的对 带头结点的单链表 的操作的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 浅用block 转
 - 下一篇: ChildWindow在Open时旋转出