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

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

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

1
1 2 3 4 5 6 8 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;
typedef struct LNode{
ElemType Data; /* 存储结点数据 */
struct LNode *Next; /* 指向下一个结点的指针 */
}LNode, *LinkList; /* 定义单链表类型 */
LinkList Read(void);
LinkList Merge(LinkList La, LinkList Lb);
void Print(LinkList L);


int main()
{
LinkList La, Lb, Lc;
La = Read();
Lb = Read();
Lc = Merge(La, Lb);
Print(Lc);

return 0;
}
LinkList Read(void){ /* 读入链表元素,以-1位结束标志*/
LinkList L,rear, temp;
ElemType data;
L = (LinkList)malloc(sizeof(LNode)); /* 链表头空结点*/
L->Data = -1;
L->Next = NULL;
rear = L;
scanf("%d", &data);
while(data!=-1){
temp = (LinkList)malloc(sizeof(LNode));
temp->Data = data;
//printf("Write:%d\n", temp->Data);
temp->Next = NULL;
rear->Next = temp;
rear = rear->Next;
scanf("%d", &data);
}
return L; /* 返回带头空结点的链表 */
}

LinkList Merge(LinkList La, LinkList Lb){
/* 输入两个有序链表的头指针,返回合并后有序链表的头指针*/
LinkList L, pa, pb, rear;
L = (LinkList)malloc(sizeof(LNode));
L->Data = -1;
L->Next = NULL;
rear = L; /* 尾插法,rear初始指向头结点*/
pa = La->Next;
pb = Lb->Next;
//printf("Start Merging...\n");
while(pa&&pb){
if(pa->Data < pb->Data){
rear->Next = pa;
//printf("Get:%d\n", pa->Data);
pa = pa->Next;
}
else{
rear->Next = pb;
//printf("Get:%d\n", pb->Data);
pb = pb->Next;
}
rear = rear->Next;
}
while(pa){
rear->Next = pa;
//printf("Get:%d\n", pa->Data);
pa = pa->Next;
rear = rear->Next;
}
while(pb){
rear->Next = pb;
//printf("Get:%d\n", pb->Data);
pb = pb->Next;
rear = rear->Next;
}
rear->Next = NULL;
/* 不删除原链表的头结点*/
return L;
}

void Print(LinkList L){
LinkList p;
int tag = 1;
p = L->Next;
while(p){
if(tag){ /* 第一个元素前面不带空格*/
printf("%d", p->Data);
tag = 0;
p = p->Next;
}
else{
printf(" %d", p->Data);
p = p->Next;
}
}
if(tag){
printf("NULL");
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×