标签:solution wol tno lists 递归 turn 另一个 结果 init
题目:https://leetcode.com/problems/merge-two-sorted-lists/
/**
* 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* l1, ListNode* l2) {
//利用递归
//哪个list为null,则说明另一个list存了所有的结果
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
//小的数放在最前面
if (l1->val >= l2 -> val) l2->next = mergeTwoLists(l1, l2->next);
else {
l1->next = mergeTwoLists(l1->next, l2);
//确保最终结果在l2上
l2 = l1;
}
return l2;
}
};
Leetcode刷题 - 多路归并类(K-way merge)
标签:solution wol tno lists 递归 turn 另一个 结果 init
原文地址:https://www.cnblogs.com/cancantrbl/p/13660806.html