- #include<stdio.h>
- #include<stdlib.h>
- typedef struct node
- {
- int data;
- struct node *next;
- }Linklist;
- Linklist *create() //创建链表,带头结点
- {
- Linklist *head;
- head=(Linklist *)malloc(sizeof(Linklist));
- head->next=NULL;
- return head;
- }
- Linklist *head_insert(Linklist *head,int value) //头插法,先插的元素排在后面
- {
- Linklist *p,*t;
- t=head;
- p=(Linklist *)malloc(sizeof(Linklist));
- p->data=value;
- p->next=t->next;
- t->next=p;
- return head;
- }
- Linklist *tail_insert(Linklist *head, int value) //尾插法
- {
- Linklist *p,*t;
- t=head;
- p=(Linklist *)malloc(sizeof(Linklist));
- p->data=value;
- while(t->next!=NULL) //当链表不为空时t向后移动
- t=t->next;
- t->next=p;
- p->next=NULL;
- return head;
- }
- Linklist *reverse(Linklist *head) //链表逆置
- {
- Linklist *p,*t;
- p=head->next;
- t=p->next;
- p->next=NULL;
- while(t!=NULL)
- {
- p=t->next;
- t->next=head->next;
- head->next=t;
- t=p;
- }
- return head;
- }
- Linklist *display(Linklist *head) //打印链表数据
- {
- Linklist *p;
- p=head->next;
- if(p==NULL)
- {
- printf("linklist is empty...\n");
- return ;
- }
- while(p!=NULL)
- {
- printf("%5d",p->data);
- p=p->next;
- }
- printf("\n");
- return head;
- }
- Linklist *delete(Linklist *head,int value) //删除结点
- {
- Linklist *p,*t;
- p=head;
- while(p->next!=NULL)
- {
- if(p->next->data==value)
- {
- t=p->next;
- p->next=t->next;
- free(t);
- t=NULL;
- }
- else
- p=p->next;
- }
- return head;
- }
- Linklist *sort(Linklist *head) //链表元素排序
- {
- int i,j,t;
- int n=0;
- Linklist *p,*q;
- p=head->next;
- while(p!=NULL)
- {
- n++;
- p=p->next;
- }
- for(i=0;i<n-1;i++) //冒泡排序
- {
- p=head->next;
- q=p->next;
- for(j=0;j<n-i-1;j++)
- {
- if(p->data > q->data)
- {
- t=p->data;
- p->data=q->data;
- q->data=t;
- }
- p=p->next;
- q=q->next;
- }
- }
- return head;
- }
- int main()
- {
- Linklist *head;
- int i,num;
- head=create();
- printf("head_insert:\n");
- for(i=1;i<20;i=i+3)
- head_insert(head,i);
- display(head);
- printf("linklist reverse:\n");
- reverse(head);
- display(head);
- printf("tail_insert:\n");
- for(i=2;i<20;i=i+4)
- tail_insert(head,i);
- display(head);
- printf("delete a node:");
- scanf("%d",&num);
- delete(head,num);
- display(head);
- printf("linklist sort:\n");
- sort(head);
- display(head);
- return 0;
- }
c语言链表操作
最新推荐文章于 2022-04-19 16:48:30 发布