-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMergeTwoSortedLists.java
More file actions
79 lines (68 loc) · 1.76 KB
/
MergeTwoSortedLists.java
File metadata and controls
79 lines (68 loc) · 1.76 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
67
68
69
70
71
72
73
74
75
76
77
78
79
package leetcode;
/**
* @author eko
*
* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
*
* Example:
*
* Input: 1->2->4, 1->3->4
* Output: 1->1->2->3->4->4
*
*/
public class MergeTwoSortedLists {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(4);
ListNode l4 = new ListNode(1);
ListNode l5 = new ListNode(3);
ListNode l6 = new ListNode(4);
l1.next = l2;
l2.next = l3;
l4.next = l5;
l5.next = l6;
ListNode result = new MergeTwoSortedLists().mergeTwoLists(l1, l4);
while (result!=null) {
System.out.println(result.val);
result = result.next;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode start;
if (l1.val < l2.val) {
start = l1;
l1 = l1.next;
} else {
start = l2;
l2 = l2.next;
}
ListNode index = start;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
index.next = l1;
l1 = l1.next;
} else {
index.next = l2;
l2 = l2.next;
}
index = index.next;
}
if (l1 != null) {
index.next = l1;
}
if (l2 != null) {
index.next = l2;
}
return start;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}