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\n");
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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM