-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedLists.cpp
More file actions
48 lines (43 loc) · 1.06 KB
/
MergeTwoSortedLists.cpp
File metadata and controls
48 lines (43 loc) · 1.06 KB
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
/**
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy(0);
ListNode* res = &dummy;
ListNode* p1 = l1;
ListNode* p2 = l2;
while (p1 && p2) {
if (p1->val <= p2->val) {
res->next = p1;
p1 = p1->next;
}
else {
res->next = p2;
p2 = p2->next;
}
res = res->next;
}
while (p1) {
res->next = p1;
p1 = p1->next;
res = res->next;
}
while (p2) {
res->next = p2;
p2 = p2->next;
res = res->next;
}
return dummy.next;
}
};