Skip to content

Commit 952adfe

Browse files
[CPP] 21. Merge Two Sorted Lists
1 parent 1fdf0fa commit 952adfe

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

cpp/21-Merge-Two-Sorted-Lists.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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* res = new ListNode(0);
15+
auto ptr = res;
16+
17+
auto ptr1 = list1;
18+
auto ptr2 = list2;
19+
20+
while (ptr1 && ptr2) {
21+
if (ptr1->val < ptr2->val) {
22+
res->next = ptr1;
23+
ptr1 = ptr1->next;
24+
res = res->next;
25+
}
26+
else {
27+
res->next = ptr2;
28+
ptr2 = ptr2->next;
29+
res = res->next;
30+
}
31+
}
32+
33+
while (ptr1) {
34+
res->next = ptr1;
35+
res = res->next;
36+
ptr1 = ptr1->next;
37+
}
38+
while (ptr2) {
39+
res->next = ptr2;
40+
res = res->next;
41+
ptr2 = ptr2->next;
42+
}
43+
44+
return ptr->next;
45+
}
46+
};

0 commit comments

Comments
 (0)