-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21. Merge Two Sorted Lists
68 lines (59 loc) · 1.64 KB
/
21. Merge Two Sorted Lists
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* list1, ListNode* list2)
{
//for one element in list1
if(list1 -> next == NULL)
{
list1 -> next = list2;
return list1;
}
ListNode* curr1 = list1;
ListNode* next1 = curr1 -> next;
ListNode* curr2 = list2;
ListNode* next2 = curr2 -> next;
while(next1 != NULL && curr2 != NULL)
{
if((curr2 -> val >= curr1 -> val) && ( curr2 -> val <= next1 -> val))
{
//add the curr2 node in b/w list1
curr1 -> next = curr2;
next2 = curr2 -> next;
curr2 -> next = next1;
//updating
curr1 = curr2;
curr2 = next2;
}
else{
curr1 = next1;
next1 = next1 -> next;
if(next1 == NULL)
{
curr1 -> next = curr2;
return list1;
}
}
}
return list1;
}
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(list1 == NULL)
return list2;
if(list2 == NULL)
return list1;
if(list1 -> val <= list2 -> val)
return merge(list1, list2);
else
return merge(list2, list1);
}
};