0%

[LeetCode] 0021 Merge Two Sorted Lists

Merge Two Sorted Lists

LeetCode - 0021 Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/

Problem Description

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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) {
ListNode dummyHead(0); // to avoid potential memory leak
auto currNode = &dummyHead;

while(l1 && l2){
auto &nextNode = (l1->val < l2->val) ? l1 : l2;
currNode->next = nextNode;
nextNode = nextNode->next;
currNode = currNode->next;
}

currNode->next = l1 ? l1 : l2;
return dummyHead.next;
}
};
  • Time complexity: O(n+m)
  • Space complexity: O(1)