-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.java
50 lines (46 loc) · 1.21 KB
/
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
42
43
44
45
46
47
48
49
50
/*
Merge two linked lists
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
}
*/
Node mergeLists(Node headA, Node headB) {
Node head = null;
Node current = null;
if (headA == null) { return headB; }
if (headB == null) { return headA; }
if (headB == null && headA == null) { return head; }
if (headA.data > headB.data) {
head = headB;
headB = headB.next;
} else {
head = headA;
headA = headA.next;
}
current = head;
while (headA != null || headB != null) {
if (headA == null) {
current.next = headB;
current = current.next;
headB = headB.next;
} else if (headB == null) {
current.next = headA;
current = current.next;
headA = headA.next;
} else {
if (headA.data > headB.data) {
current.next = headB;
current = current.next;
headB = headB.next;
} else {
current.next = headA;
current = current.next;
headA = headA.next;
}
}
}
return head;
}