1. 题意
合并两个有序链表。
2. 题解
2.1 递归
如果其中一个链表为空了,就直接返回另一个链表的头节点。
如果两个都不空,则取其中较小的链表头节点。再递归处理剩下的链表。
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if ( list1 == NULL )
return list2;
if ( list2 == NULL )
return list1;
if ( list1->val < list2->val) {
list1->next = mergeTwoLists( list1->next, list2 );
return list1;
}
else {
list2->next = mergeTwoLists( list1, list2->next);
return list2;
}
}
};
2.2 迭代
可以用一个头节点来减少复杂度。
同时我们只需要维护新链表的尾节点即可。
我们在循环中处理两个链表均非空的情况,当处理完成后最多只有一个
链表非空了再单独处理一下就好了。
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
auto dumpNode = make_shared<ListNode>(-1);
ListNode *tail = dumpNode.get();
while ( list1 && list2 ) {
if ( list1->val < list2->val ) {
tail->next = list1;
tail = list1;
list1 = list1->next;
}
else {
tail->next = list2;
tail = list2;
list2 = list2->next;
}
}
tail->next = list1 == NULL ? list2 : list1;
return dumpNode->next;
}
};