數據結構實驗之鏈表四:有序鏈表的歸并
?
Time Limit: 1000MS Memory limit: 65536K
題目描述
分別輸入兩個有序的整數序列(分別包含M和N個數據),建立兩個有序的單鏈表,將這兩個有序單鏈表合并成為一個大的有序單鏈表,并依次輸出合并后的單鏈表數據。
輸入
第一行輸入M與N的值;?
第二行依次輸入M個有序的整數;
第三行依次輸入N個有序的整數。
第二行依次輸入M個有序的整數;
第三行依次輸入N個有序的整數。
輸出
輸出合并后的單鏈表所包含的M+N個有序的整數。
示例輸入
6 5 1 23 26 45 66 99 14 21 28 50 100
示例輸出
1 14 21 23 26 28 45 50 66 99 100
提示
不得使用數組!
來源
示例程序
#include <stdio.h> #include <stdlib.h> struct node {int data;struct node *next; }*head1,*head2; struct node *creat(int n) {struct node *head,*tail,*p;head=(struct node *)malloc(sizeof(struct node));head->next=NULL;p=head;while(n--){tail=(struct node *)malloc(sizeof(struct node));scanf("%d",&tail->data);tail->next=p->next;p->next=tail;p=tail;}return(head); }; struct node * merge(struct node *head1,struct node *head2) {struct node *p1,*p2,*tail;p1=head1->next;p2=head2->next;tail=head1;free(head2);while(p1 && p2)if(p1->data<p2->data){tail->next=p1;tail=p1;p1=p1->next;}else{tail->next=p2;tail=p2;p2=p2->next;}if(p1)tail->next=p1;elsetail->next=p2;return (head1); } int main() {int n,m;struct node *head1,*head2,*p;scanf("%d%d",&n,&m);head1=creat(n);head2=creat(m);p=merge(head1,head2);while(p->next !=NULL){if(p->next->next!=NULL)printf("%d ",p->next->data);elseprintf("%d\n",p->next->data);p=p->next;}return 0; }
?