-
Notifications
You must be signed in to change notification settings - Fork 0
/
0021_Merge_Two_Sorted_Lists.cs
50 lines (47 loc) · 1.17 KB
/
0021_Merge_Two_Sorted_Lists.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
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
ListNode ret = null, tail = null;
void AddNode(ListNode node) {
if (ret == null) {
ret = tail = node;
} else {
tail.next = node;
tail = tail.next;
}
}
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
while (l1 != null && l2 != null) {
ListNode next;
if (l1.val < l2.val) {
next = l1;
l1 = l1.next;
} else {
next = l2;
l2 = l2.next;
}
AddNode(next);
}
while (l1 != null) {
ListNode next = l1;
l1 = l1.next;
AddNode(next);
}
while (l2 != null) {
ListNode next = l2;
l2 = l2.next;
AddNode(next);
}
//Console.WriteLine($"ret.val = '{ret?.val}'");
return ret;
}
}