-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0021-merge-two-sorted-lists.c
46 lines (36 loc) · 1.03 KB
/
0021-merge-two-sorted-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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
if (list1 == NULL && list2 == NULL) {
return NULL;
} else if (list1 != NULL && list2 == NULL) {
return list1;
} else if (list2 != NULL && list1 == NULL) {
return list2;
}
struct ListNode* temp_node = NULL;
if (list1 -> val < list2 -> val) {
temp_node = list1;
list1 = list1 -> next;
} else {
temp_node = list2;
list2 = list2 -> next;
}
struct ListNode* root = temp_node;
while((list1 != NULL) || (list2 != NULL)) {
if ((list2 == NULL) || ((list1 != NULL) && (list1 -> val < list2 -> val))) {
temp_node -> next = list1;
list1 = list1 -> next;
} else {
temp_node -> next = list2;
list2 = list2 -> next;
}
temp_node = temp_node -> next;
}
return root;
}