-
Notifications
You must be signed in to change notification settings - Fork 1
/
0021_merge_two_lists.c
47 lines (43 loc) · 1.02 KB
/
0021_merge_two_lists.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
/**
* Author: Xiangyue Cai
* Date: 2019-08-27
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
struct ListNode *head , *merged, *tmp;
head = merged = tmp = NULL;
for (;;) {
if (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
tmp= l1;
l1 = l1->next;
}
else {
tmp = l2;
l2 = l2->next;
}
if (merged) merged->next = tmp;
merged = tmp;
if (!head) head = merged;
}
else if (l1 == NULL && l2 != NULL) {
merged->next = l2;
break;
}
else if(l1 != NULL && l2 == NULL) {
merged->next = l1;
break;
}
else
break;
}
return head;
}