/*合並兩個有序鏈表,將兩個升序鏈表合並為一個新的升序鏈表並返回。 新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。 例如:輸入 1->2->4,1->3->4->5,輸出:1->1->2->3->4->4->5 */ #include <stdio.h> #include <stdlib.h> #define LEN sizeof(struct node) typedef struct node{ int data; struct node *next; }List; List *selectsort(List *head) { List *p,*q,*min; int tmp; for(p=head;p->next!=NULL;p=p->next) { min=p; for(q=p->next;q!=NULL;q=q->next) if(q->data<min->data) min=q; if(min!=p) { tmp=p->data; p->data=min->data; min->data=tmp; } } return head; } List *creat()//建立鏈表以負數結束 { printf("請輸入創建鏈表結點值,以-1結束\n"); List *head=NULL,*p1,*p2; p1=p2=(List*)malloc(LEN); scanf("%d",&p1->data); while(p1->data>=0) { if(head==NULL)head=p1; else p2->next=p1; p2=p1; p1=(List*)malloc(LEN); scanf("%d",&p1->data); } p2->next=NULL; return head; } void print(List *head)//輸出鏈表 { List *p=head; if(head==NULL)return; while(p) { printf("%4d->",p->data); p=p->next; } printf(" end.\n"); } List *merge(List *h1,List *h2)// 合並兩個有序鏈表 { if(h1==NULL) return h2; if(h2==NULL) return h1; List *p1=h1,*p2=h2,*head=NULL; if(p1->data > p2->data)//先確定頭結點 { head=p2; p2=p2->next; } else { head=p1; p1=p1->next; } List *current=head;//current始終指向head鏈表的最后一個節點 while(p1!=NULL && p2!=NULL) { if(p1->data >p2->data) { current->next=p2; current=p2; p2=p2->next; } else { current->next=p1; current=p1; p1=p1->next; } } if(p1==NULL)//p1鏈表為空,就把剩下的p2鏈表直接加入head末尾 current->next=p2; if(p2==NULL) current->next=p1; return head; } int main() { List *h1,*h2,*head; printf("請創建鏈表1和鏈表2:"); h1=selectsort(creat(h1)); h2=selectsort(creat(h2)); printf("排序結果:\n"); print(h1);print(h2); printf("兩個鏈表合並后的結果:\n"); head=merge(h1,h2); print(head); }
運行結果:

