Skip to content

Commit d055b48

Browse files
committed
Time: 19 ms (18.16%), Space: 14.8 MB (81.48%) - LeetHub
1 parent ab20857 commit d055b48

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
14+
ListNode* dummy = new ListNode(0);
15+
ListNode* curr = dummy;
16+
17+
// curr l11 l12 ....
18+
// curr -> l11
19+
// ^ ^
20+
while (list1 != NULL and list2 != NULL) {
21+
if (list1->val <= list2->val) {
22+
curr->next = list1;
23+
list1 = list1->next;
24+
} else {
25+
curr->next = list2;
26+
list2 = list2->next;
27+
}
28+
curr = curr->next;
29+
}
30+
31+
// curr
32+
// n n n
33+
if (list1 != NULL)
34+
curr->next = list1;
35+
36+
if (list2 != NULL)
37+
curr->next = list2;
38+
39+
return dummy->next;
40+
}
41+
};

0 commit comments

Comments
 (0)