-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedLists.java
More file actions
68 lines (65 loc) · 1.67 KB
/
Copy pathMergeTwoSortedLists.java
File metadata and controls
68 lines (65 loc) · 1.67 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
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
boolean end1 = list1 == null;
boolean end2 = list2 == null;
ListNode head = null;
if (end2) {
return list1;
}
else if (end1) {
return list2;
}
// Create head
if ((!end1 && !end2) && list1.val < list2.val) {
head = list1;
if (list1.next != null) {
list1 = list1.next;
}
else {
end1 = true;
}
}
else if ((!end1 && !end2) && list1.val >= list2.val) {
head = list2;
if (list2.next != null) {
list2 = list2.next;
}
else {
end2 = true;
}
}
ListNode current = head;
// Keep merging the lists
while (!end1 && !end2) {
if (list1.val < list2.val) {
current.next = list1;
if (list1.next != null) {
list1 = list1.next;
}
else {
end1 = true;
}
}
else {
current.next = list2;
if (list2.next != null) {
list2 = list2.next;
}
else {
end2 = true;
}
}
current = current.next;
}
// Copy list2
if (!end2) {
current.next = list2;
}
// Copy list1
else if (!end1) {
current.next = list1;
}
// Return head
return head;
}
}