以下是一个合并两个有序链表的C++代码示例:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int value) : val(value), next(nullptr) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
// 创建一个新的头结点用于存放合并后的链表
ListNode* dummy = new ListNode(0);
ListNode* current = dummy;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val <= l2->val) {
current->next = l1;
l1 = l1->next;
} else {
current->next = l2;
l2 = l2->next;
}
current = current->next;
}
// 将剩余的节点连接到合并后的链表末尾
if (l1 != nullptr) {
current->next = l1;
}
if (l2 != nullptr) {
current->next = l2;
}
// 返回合并后的链表,跳过初始的虚拟头结点
return dummy->next;
}
// 创建一个简单的链表用于示例
ListNode* createLinkedList(int arr[], int size) {
ListNode *head, *current;
head = current = NULL;
for (int i = 0; i < size; ++i) {
ListNode *node = new ListNode(arr[i]);
if (!head)
head = current = node;
else {
current->next = node;
current = node;
}
}
return head;
}
// 打印链表
void printLinkedList(ListNode* head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
// 创建两个有序链表用于合并
int arr1[] = { 1, 3, 5 };
int arr2[] = { 2, 4, 6 };
ListNode* l1 = createLinkedList(arr1, sizeof(arr1) / sizeof(arr1[0]));
ListNode* l2 = createLinkedList(arr2, sizeof(arr2) / sizeof(arr2[0]));
// 合并两个链表
ListNode* mergedList = mergeTwoLists(l1, l2);
// 输出合并后的链表
cout << "Merged List: ";
printLinkedList(mergedList);
// 释放内存
delete l1;
delete l2;
return 0;
}
你可以根据实际需求修改两个有序链表的数据和顺序,然后运行上述代码以合并这两个链表,并输出合并后的结果。
内容由零声教学AI助手提供,问题来源于学员提问




