在这个问题中,我们的目标是合并两个递增的有序链表,并要求结果链表仍然使用原来两个链表的存储空间,而不另外占用其他的存储空间。这个任务可以通过使用一种称为"归并"的技术来解决。
以下是用C语言解决这个问题的基本思路:
- 定义一个新的链表,我们称之为结果链表。这个链表在开始时是空的。
- 初始化两个指针,一个指向第一个链表的头部,另一个指向第二个链表的头部。
- 进行一次循环,比较两个链表的头部元素。将较小的元素添加到结果链表中,并将相应的指针向后移动一位。
- 如果一个链表的所有元素都被添加到结果链表中(即该链表的头部指针变为NULL),而另一个链表还有剩余元素,那么将剩余的元素全部添加到结果链表中。
- 打印结果链表。
代码如下:
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* mergeTwoLists(struct Node* l1, struct Node* l2) {
struct Node* dummy = (struct Node*)malloc(sizeof(struct Node)); //定义一个哑节点作为结果链表的头部
struct Node* tail = dummy; //定义一个指针tail,初始化为哑节点,用于添加元素到结果链表
while(l1 != NULL && l2 != NULL) { //当两个链表都不为空时
if(l1->data <= l2->data) { //比较两个链表头部元素,将较小的添加到结果链表
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next; //移动tail指针到下一个节点
}
if(l1 != NULL) tail->next = l1; //如果l1还有剩余元素,将l1添加到结果链表末尾
if(l2 != NULL) tail->next = l2; //如果l2还有剩余元素,将l2添加到结果链表末尾
return dummy->next; //返回结果链表的头部(跳过哑节点)
}
归并的思想来解决该问题
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node* next;
};
// 新建一个链表节点
struct Node* newNode(int data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// 归并两个有序链表
struct Node* mergeTwoLists(struct Node* l1, struct Node* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
// 找到两个链表的最后一个节点
struct Node* last1 = l1;
while (last1->next != NULL) last1 = last1->next;
struct Node* last2 = l2;
while (last2->next != NULL) last2 = last2->next;
// 合并两个链表
if (last1->data <= last2->data) {
last1->next = mergeTwoLists(last1->next, l2);
return l1;
} else {
last2->next = mergeTwoLists(l1, last2->next);
return l2;
}
}
// 打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* l1 = newNode(1);
l1->next = newNode(3);
l1->next->next = newNode(5);
l1->next->next->next = NULL;
struct Node* l2 = newNode(2);
l2->next = newNode(4);
l2->next->next = newNode(6);
l2->next->next->next = NULL;
struct Node* result = mergeTwoLists(l1, l2);
printList(result); // 输出:1 2 3 4 5 6
return 0;
}