-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21. Merge Two Sorted Lists
55 lines (51 loc) · 1.18 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head = NULL;
if(l1 && l2){
if(l1->val <= l2->val){
head = l1;
l1 = l1->next;
}else{
head = l2;
l2 = l2->next;
}
struct ListNode* p = head;
for(p=head;p->next;p=p->next){
if(l1->val <= l2->val){
p->next = l1;
l1 = l1->next;
}else{
p->next = l2;
l2 = l2->next;
}
}
while(p){
if(l1 == NULL){
p->next = l2;
if(l2 != NULL){
l2 = l2->next;
}
p = p->next;
}else{
p->next = l1;
if(l1 != NULL){
l1 = l1->next;
}
p = p->next;
}
}
}else if(l1 || l2){
if(l1 == NULL){
head = l2;
}else{
head = l1;
}
}
return head;
}