-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path021_Merge_Two_Sorted_Lists.cpp
More file actions
66 lines (64 loc) · 1.33 KB
/
021_Merge_Two_Sorted_Lists.cpp
File metadata and controls
66 lines (64 loc) · 1.33 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode *head, *cur;
head = new ListNode(-1);
cur = head;
for(;l1 != NULL; cur = cur->next)
{
if( l2 == NULL)
{
cur->next = l1;
return head->next;
}
if( l1->val < l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
}
cur->next = l2;
return head->next;
}
};
int main(int argc, char const *argv[])
{
ListNode a(1), b(3), c(5), d(6), e(7);
ListNode f(2), g(4), h(8), i(10), j(11);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
f.next = &g;
g.next = &h;
h.next = &i;
i.next = &j;
Solution sol;
ListNode* res = sol.mergeTwoLists(&a, &f);
while( res != NULL)
{
cout<<res->val<<"\t";
res =res->next;
}
return 0;
}