-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeTwoSortedLists.java
52 lines (47 loc) · 1.34 KB
/
MergeTwoSortedLists.java
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
package leetcode.easy;
public class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = null;
ListNode tail = null;
while (l1 != null && l2 != null) {
ListNode val = null;
if (l1.val <= l2.val) {
val = new ListNode(l1.val);
l1 = l1.next;
} else if (l2.val <= l1.val) {
val = new ListNode(l2.val);
l2 = l2.next;
}
if (result == null) {
result = val;
tail = result;
} else {
tail.next = val;
tail = tail.next;
}
}
while (l1 != null) {
ListNode val1 = new ListNode(l1.val);
if (result == null) {
result = val1;
tail = result;
} else {
tail.next = val1;
tail = tail.next;
}
l1 = l1.next;
}
while (l2 != null) {
ListNode val1 = new ListNode(l2.val);
if (result == null) {
result = val1;
tail = result;
} else {
tail.next = val1;
tail = tail.next;
}
l2 = l2.next;
}
return result;
}
}