-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedList.cc
More file actions
37 lines (32 loc) · 1005 Bytes
/
MergeTwoSortedList.cc
File metadata and controls
37 lines (32 loc) · 1005 Bytes
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
// https://oj.leetcode.com/problems/merge-two-sorted-lists/
namespace MergeTwoSortedList {
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == NULL && l2 == NULL) {
return NULL;
}
ListNode * dummy = new ListNode(0);
ListNode * cur = dummy;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1 != NULL) {
cur->next = l1;
}
if (l2 != NULL) {
cur->next = l2;
}
ListNode * res = dummy->next;
delete dummy;
return res;
}
};
}