-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0021-merge-two-sorted-lists.cpp
39 lines (35 loc) · 1.07 KB
/
0021-merge-two-sorted-lists.cpp
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
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode *out = NULL, *cur = NULL;
while(1) {
if (!list1 && !list2)
return out;
if (!list2 || (list1 && list1->val <= list2->val)) {
ListNode *node = new(ListNode);
node->val = list1->val;
node->next = nullptr;
if (out == NULL) {
out = node;
} else {
cur->next = node;
}
cur = node;
list1 = list1->next;
}
else if (!list1 || (list2 && list2->val <= list1->val)) {
ListNode *node = new(ListNode);
node->val = list2->val;
node->next = nullptr;
if (out == NULL) {
out = node;
} else {
cur->next = node;
}
cur = node;
list2 = list2->next;
}
}
return out;
}
};