-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathMergeTwoSortedLists.java
More file actions
48 lines (35 loc) · 816 Bytes
/
MergeTwoSortedLists.java
File metadata and controls
48 lines (35 loc) · 816 Bytes
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
package leetcode;
import util.ListNode;
/**
* Created by nikoo28 on 7/10/19 12:21 AM
*/
class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode pointer;
ListNode answer;
if(l1.val < l2.val) {
answer = new ListNode(l1.val);
l1 = l1.next;
} else {
answer = new ListNode(l2.val);
l2 = l2.next;
}
pointer = answer;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
pointer.next = new ListNode(l1.val);
l1 = l1.next;
} else {
pointer.next = new ListNode(l2.val);
l2 = l2.next;
}
pointer = pointer.next;
}
pointer.next = l1 == null ? l2 : l1;
return answer;
}
}