-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
41 lines (35 loc) · 934 Bytes
/
Solution.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
// github.com/RodneyShag
/*
class SinglyLinkedListNode {
int data;
SinglyLinkedListNode next;
}
*/
// Time Complexity: O(n + m)
// Space Complexity: O(1)
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode currA, SinglyLinkedListNode currB) {
if (currA == null) {
return currB;
} else if (currB == null) {
return currA;
}
SinglyLinkedListNode result = new SinglyLinkedListNode(0); // dummy/placeholder ListNode
SinglyLinkedListNode n = result;
while (currA != null && currB != null) {
if (currA.data < currB.data) {
n.next = currA;
currA = currA.next;
} else {
n.next = currB;
currB = currB.next;
}
n = n.next;
}
/* Attach the remaining elements */
if (currA == null) {
n.next = currB;
} else {
n.next = currA;
}
return result.next;
}