-
Notifications
You must be signed in to change notification settings - Fork 93
/
Merge_two_sorted_list.cpp
57 lines (45 loc) · 1.43 KB
/
Merge_two_sorted_list.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
class Solution {
public:
ListNode* solve(ListNode*list1, ListNode* list2){
//if there is only one node
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)){
curr1->next = curr2;
next2 = curr2->next;
curr2->next = next1;
//Update pointer
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 solve(list1, list2);
}
else{
return solve(list2, list1);
}
}
};