对 带头结点的单链表 的操作

//带头结点的单链表

#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;

}

posted on 2011-08-03 14:26  原来...  阅读(1042)  评论(1编辑  收藏  举报

导航