C語言鏈表的建立,排序和合并

來源:互聯網
上載者:User

先建立兩個亂序的鏈表,再依次排序。然後將兩個有序鏈表合并。

自己閑來練手的程式,不足之處望指出。

#include<stdio.h>#include<malloc.h>typedef struct node{int num;struct node *next;}link;void create(link *head){link *p,*q;p=head;int i;for(i=0;i<5;i++){q=(link *)malloc(sizeof(link));p->next=q;p=q;}p=head->next;while(p!=NULL){scanf("%d",&(p->num));p=p->next;}}void sort(link *head){link *p,*q,*r,*u;p=head->next;head->next=NULL;while(p){r=head;q=head->next;while(q&&q->num<=p->num){r=q;q=q->next;}u=p->next;p->next=r->next;r->next=p;p=u;}}link *merge(link *a,link*b){link *p, *q,*pc;p=a->next;q=b->next;link *c=(link*)malloc(sizeof(link));pc=c;while(p&&q){if(p->num<=q->num){pc->next=p;pc=pc->next;p=p->next;}else{pc->next=q;pc=pc->next;q=q->next;}}pc->next=p?p:q;free(b);return c;}void main(){link * a,*b,*c;link *pa,*pb,*pc;a=(link*)malloc(sizeof(link));b=(link*)malloc(sizeof(link));printf("create a\n");create(a);sort(a);pa=a->next;printf("sort a is;\n");while(pa){printf("%d ",pa->num);pa=pa->next;}printf("\n");printf("create b\n");create(b);sort(b);pb=b->next;printf("sort b is;\n");while(pb){printf("%d ",pb->num);pb=pb->next;}printf("\n");c=merge(a,b);pc=c->next;printf("merge is:");while(pc){printf("%d ",pc->num);pc=pc->next;}printf("\n");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.