-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0021-MergeTwoSortedLists.cs
117 lines (112 loc) · 3.33 KB
/
0021-MergeTwoSortedLists.cs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using Xunit;
using Util;
using System.Collections.Generic;
using System.Collections;
namespace MergeTwoSortedLists
{
public class Solution
{
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode res = null;
ListNode node = null;
ListNode n1 = l1, n2 = l2;
while (true)
{
if (n1.val <= n2.val)
{
if (res == null)
{
res = new ListNode(n1.val);
node = res;
}
else
{
node.next = new ListNode(n1.val);
node = node.next;
}
if (n1.next != null)
{
n1 = n1.next;
}
else
{
while (true)
{
node.next = new ListNode(n2.val);
node = node.next;
if (n2.next == null)
break;
n2 = n2.next;
}
break;
}
}
else
{
if (res == null)
{
res = new ListNode(n2.val);
node = res;
}
else
{
node.next = new ListNode(n2.val);
node = node.next;
}
if (n2.next != null)
{
n2 = n2.next;
}
else
{
while (true)
{
node.next = new ListNode(n1.val);
node = node.next;
if (n1.next == null)
break;
n1 = n1.next;
}
break;
}
}
}
return res;
}
}
public class Test
{
static public void Run()
{
Console.WriteLine("MergeTwoSortedLists");
ListNode l1, l2;
ListNode exp, res;
using (new Timeit())
{
// Input: 1->2->4, 1->3->4
// Output: 1->1->2->3->4->4
l1 = ListNode.FromList(new int[] { 1, 2, 4 });
l2 = ListNode.FromList(new int[] { 1, 3, 4 });
exp = ListNode.FromList(new int[] { 1, 1, 2, 3, 4, 4 });
res = new Solution().MergeTwoLists(l1, l2);
Assert.Equal(exp, res);
}
using (new Timeit())
{
// Input: [],[]
// Output: []
l1 = null;
l2 = null;
exp = null;
res = new Solution().MergeTwoLists(l1, l2);
Assert.Equal(exp, res);
}
}
}
}