5-51 两个有序链表序列的合并 (20分)

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用-11表示序列的结尾(-11不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 3 5 -1
2 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10



 1 #include "stdio.h"
 2 
 3 typedef struct Node
 4 {
 5     int data;
 6     struct Node *next;
 7 }Node, *linkList;
 8 
 9 void InitList(linkList *L)
10 {
11     (*L) = (linkList)malloc(sizeof(Node));
12     (*L)->next = NULL;
13 }
14 
15 void creat(linkList L)
16 {
17     Node *s, *r = L;
18     int num, flag = 1;
19     while(flag)
20     {
21         scanf("%d", &num);
22         if(num >= 0) //num脢脟脪陋虏氓脠毛碌脛脭陋脣脴
23         {
24             s = (linkList)malloc(sizeof(Node));
25             s->data = num;
26             r->next = s;
27             r = r->next;
28         }
29         else
30         {
31             flag = 0;
32             r->next = NULL;
33         }
34     }
35 }
36 
37 void print(Node * L)
38 {
39     Node * t = L->next;
40     int firstNum = 1;
41     if(t == NULL) printf("NULL
");
42     while(t != NULL)
43     {
44         if(firstNum)
45         {
46             printf("%d", t->data);
47             firstNum = 0;
48         }
49         else
50             printf(" %d", t->data);
51         t = t->next;
52     }
53 }
54 
55 void sort(Node *L1, Node *L2, Node *L3)
56 {
57     Node *s1 = L1->next, *s2 = L2->next;
58     Node *r = L3;
59     while(s1 != NULL && s2 != NULL)
60     {
61         if(s1->data < s2->data)
62         {
63             r->next = s1;
64             r = r->next;
65             s1 = s1->next;
66         }
67         else
68         {
69             r->next = s2;
70             r = r->next;
71             s2 = s2->next;
72         }
73     }
74     if(s1 != NULL)
75         r->next = s1;
76     else
77         r->next = s2;
78 
79     // return s3;
80 }
81 
82 int main(int argc, char const *argv[])
83 {
84     Node *L1, *L2, *L3;
85     InitList(&L1);
86     InitList(&L2);
87     InitList(&L3);
88     creat(L1);
89     creat(L2);
90     sort(L1, L2, L3);
91     print(L3);
92     return 0;
93 }
原文地址:https://www.cnblogs.com/hello-lijj/p/7096425.html