-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path021_MergeTwoSortedList.c
56 lines (51 loc) · 1019 Bytes
/
021_MergeTwoSortedList.c
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//20.8%
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
//Check boundary conditions
if(!l1)
return l2;
if(!l2)
return l1;
struct ListNode *ptr1 = l1, *ptr2 = l2;
struct ListNode *rst = NULL, *head = NULL;
//Define first node from where
if(ptr1 -> val < ptr2 -> val){
rst = ptr1;
ptr1 = ptr1 -> next;
}
else{
rst = ptr2;
ptr2 = ptr2 -> next;
}
head = rst;
//FIrst round circulation
while(ptr1 && ptr2){
if(ptr1 -> val < ptr2 -> val){
rst -> next = ptr1;
ptr1 = ptr1 -> next;
}
else{
rst -> next = ptr2;
ptr2 = ptr2 -> next;
}
rst = rst -> next;
}
//Second round circulation
while(ptr1){
rst -> next = ptr1;
ptr1 = ptr1 -> next;
rst = rst -> next;
}
while(ptr2){
rst -> next = ptr2;
ptr2 = ptr2 -> next;
rst = rst -> next;
}
return head;
}