- #include <stdio.h>
- #define END_elem 0
- struct node
- {
- int date;
- struct node * next;
- };
- //链表创建
- node * creat()
- {
- int x;
- node *head,*last,*p;
- head=new node();
- last=head;
- scanf("%d",&x);
- while(x!=END_elem)
- {
- p=new node();
- p->date=x;
- last->next=p;
- last=p;
- scanf("%d",&x);
- }
- head=head->next;
- last->next=NULL;
- return head;
- }
- //单链表测长
- int lenght(node *head)
- {
- int n=0;
- node *p=head;
- while(p!=NULL)
- {
- p=p->next;
- n++;
- }
- return n;
- }
- //链表排序
- node *sort(node *head,int n)
- {
- int temp;
- node *p;
- if(head==NULL||head->next==NULL)
- return head;
- for(int i=0;i<n-1;i++)
- {
- p=head;
- for(int j=0;j<n-1-i;j++)
- {
- if(p->date>p->next->date)
- {
- temp=p->date;
- p->date=p->next->date;
- p->next->date=temp;
- }
- p=p->next;
- }
- }
- return head;
- }
- //链表插入
- node * insert(node *head,int num)
- {
- node *p,*q,*t;
- p=head;
- t=new node();
- t->date=num;
- while(num>p->date&&p->next!=NULL)
- {
- q=p;
- p=p->next;
- }
- if(num<=p->date)
- {
- if(p==head)
- {
- t->next=p;
- head=t;
- }
- else
- {
- t->next=p;
- q->next=t;
- }
- }
- else//把插入点定在表尾
- {
- p->next=t;
- t->next=NULL;
- }
- return head;
- }
- //链表输出
- void print(node *head)
- {
- struct node *p=head;
- while(p!=NULL)
- {
- printf("%d ",p->date);
- p=p->next;
- }
- }
- //链表删除
- node *del(node *head,int num)
- {
- node *p,*q;
- p=head;
- while(num!=p->date&&p->next!=NULL)
- {
- q=p;
- p=p->next;
- }
- if(p->date==num)
- {
- if(p==head)
- {
- head=p->next;
- delete p;
- }
- else
- {
- q->next=p->next;
- delete p;
- }
- }
- else
- printf("Didn't Fond The Num!");
- return head;
- }
- //链表逆序
- node *reverse(node *head)
- {
- node *p1,*p2,*p3;
- p1=head;
- p2=head->next;
- while(p2)
- {
- p3=p2->next;
- p2->next=p1;
- p1=p2;
- p2=p3;
- }
- head->next=NULL;
- head=p1;
- return head;
- }
- void main()
- {
- struct node *head;
- int n,m;
- printf("链表创建,输入数字: ");
- head=creat();
- print(head);
- n=lenght(head);
- printf("链表的长度为 %d ",n);
- printf("链表排序: ");
- head=sort(head,n);
- print(head);
- printf("输入要插入链表的数: ");
- scanf("%d",&m);
- printf("插入后的链表: ");
- head=insert(head,m);
- print(head);
- printf("链表逆序: ");
- head=reverse(head);
- print(head);
- }