- 题目来源:
浙江大学在慕课网上开设的《数据结构》课,陈越老师、何钦铭老师主讲,课后作业的一道题。
https://pintia.cn/problem-sets/1134360184290500608/problems/1138764336949059584
- 题目描述:
- 题目思路:
首先一定要注意,这个链表是有头节点的,再就是在Merge()函数中声明了一个struct Node* Rear变量,在进行挂接操作的时候,Rear = Rear->Next;这条语句不要忘记。再就是当遍历完两个链表之后,有可能出现一个L1链表的长度比L2链表的长度长,这个时候就要记得把L1直接挂接在Rear后面。
- C语言实现:
List Merge(List L1, List L2)
{
struct Node* tempL1 = L1;
struct Node* tempL2 = L2;
struct Node* Rear;
struct Node* l = (struct Node*)malloc(sizeof(struct Node));
l->Next = NULL;
Rear = l;
while (L1->Next != NULL && L2->Next != NULL)
{
if (L1->Next->Data < L2->Next->Data) //如果L1比较小
{
Rear->Next = L1->Next;
L1->Next = L1->Next->Next;
Rear->Next->Next = NULL;
Rear = Rear->Next;
}
else
{
Rear->Next = L2->Next;
L2->Next = L2->Next->Next;
Rear->Next->Next = NULL;
Rear = Rear->Next;
}
}
while (L1->Next != NULL)
{
Rear->Next = L1->Next;
L1->Next = NULL;
}
while (L2->Next != NULL)
{
Rear->Next = L2->Next;
L2->Next = NULL;
}
return l;
}