先建立兩個亂序的鏈表,再依次排序。然後將兩個有序鏈表合并。
自己閑來練手的程式,不足之處望指出。
#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");}