-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge2SortedLL.cpp
64 lines (55 loc) · 1.58 KB
/
merge2SortedLL.cpp
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
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* sortLL(ListNode* list1, ListNode* list2){
//if list1 has only one node
if(list1->next == NULL){
list1->next = list2;
return list1;
}
ListNode* curr1 = list1;
ListNode* next1 = curr1->next;
ListNode* curr2 = list2;
ListNode* next2;
while(next1!=NULL && curr2!=NULL){
if((curr2->val >= curr1->val) && (curr2->val <= next1->val)){
//node addition
curr1->next = curr2;
next2 = curr2->next;
curr2->next = next1;
//pointer updation
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 sortLL(list1,list2);
}
else{
return sortLL(list2,list1);
}
}
};