https://leetcode-cn.com/problems/merge-two-sorted-lists/
Combine the two ascending linked lists into a new ascending linked list and return. The new linked list is composed of all the nodes of the given two linked lists.
Examples:
Input: 1-> 2-> 4, 1-> 3-> 4
Output: 1-> 1-> 2-> 3-> 4-> 4
Solution 1
Recursively. 8ms, 7.1mb
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
if (l1->val <= l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
Solution 2
Iterate. 20 ms 7 MB
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* res = new ListNode(-1);
ListNode* p = res;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val <= l2->val) {
p->next = l1;
l1 = l1->next;
} else {
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
p->next = l1 == nullptr ? l2 : l1;
return res->next;
}
};
EOF