File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments