C++ 合并两个有序链表:完整代码和示例
#include
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); // 创建一个虚拟节点 ListNode* cur = dummy; // cur指向虚拟节点
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1 != NULL) { // 如果l1还有剩余节点,直接将其接到cur后面
cur->next = l1;
}
if (l2 != NULL) { // 如果l2还有剩余节点,直接将其接到cur后面
cur->next = l2;
}
return dummy->next; // 返回虚拟节点的下一个节点,即合并后的链表的头节点
}
void printList(ListNode* head) { ListNode* cur = head; while (cur != NULL) { cout << cur->val << ' '; // 修改为单引号 cur = cur->next; } cout << endl; }
int main() { ListNode* l1 = new ListNode(1); l1->next = new ListNode(2); l1->next->next = new ListNode(4);
ListNode* l2 = new ListNode(1);
l2->next = new ListNode(3);
l2->next->next = new ListNode(4);
ListNode* merged = mergeTwoLists(l1, l2);
printList(merged);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/p3QD 著作权归作者所有。请勿转载和采集!