有序链表的归并

数据结构实验之链表四:有序链表的归并

Time Limit: 1000MS Memory limit: 65536K

题目描述

分别输入两个有序的整数序列(分别包含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
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 struct vode
 4 {
 5     int date;
 6     struct vode *next;
 7 };
 8 int main()
 9 {
10     int m,n;
11     scanf("%d%d",&m,&n);
12     struct vode *head1,*head2,*tail,*p;
13     head1=(struct vode *)malloc(sizeof(struct vode ));
14     head1->next=NULL;
15     tail=head1;
16     int i;
17     for(i=1;i<=m;i++)
18     {
19         p=(struct vode *)malloc(sizeof(struct vode));
20         p->next=NULL;
21         scanf("%d",&p->date);
22         tail->next=p;
23         tail=p;
24     }
25     head2=(struct vode *)malloc(sizeof(struct vode ));
26     head2->next=NULL;
27     tail=head2;
28     for(i=1;i<=n;i++)
29     {
30         p=(struct vode *)malloc(sizeof(struct vode));
31         p->next=NULL;
32          scanf("%d",&p->date);
33         tail->next=p;
34         tail=p;
35     }
36     struct vode *p1,*p2;
37     p1=head1->next;
38     p2=head2->next;
39     tail=head1;
40     while(p1&&p2)
41     {
42         if(p1->date>p2->date)
43         {
44             tail->next=p2;
45             tail=p2;
46             p2=p2->next;
47         }
48         else
49         {
50             tail->next=p1;
51             tail=p1;
52             p1=p1->next;
53         }
54     }
55     if(p1)tail->next=p1;
56     else tail->next=p2;
57     p=head1->next;
58     int s=0;
59     while(p)
60     {
61         if(s==0)
62         {
63             printf("%d",p->date);
64             s=1;
65         }
66         else
67         {
68             printf(" %d",p->date);
69         }
70         p=p->next;
71     }
72     printf("
");
73 return 0;
74 }
View Code
原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/3264614.html