-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMerge-to-List.cpp
More file actions
48 lines (46 loc) · 1.09 KB
/
Merge-to-List.cpp
File metadata and controls
48 lines (46 loc) · 1.09 KB
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
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* head=nullptr, *c1=list1, *c2=list2, *p;
if(c1!=nullptr && c2!=nullptr){
if(c1->val<=c2->val){
head=c1;
p=c1;
c1=c1->next;
p->next=nullptr;
}else{
head=c2;
p=c2;
c2=c2->next;
p->next=nullptr;
}
}
else if(c1!=nullptr){
return c1;
}
else{
return c2;
}
while(c1!=nullptr && c2!=nullptr){
if(c1->val<=c2->val){
p->next=c1;
p=c1;
c1=c1->next;
p->next=nullptr;
}
else{
p->next=c2;
p=c2;
c2=c2->next;
p->next=nullptr;
}
}
if(c1!=nullptr){
p->next=c1;
}
else{
p->next=c2;
}
return head;
}
};