-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge Point of Two Linked Lists.java
46 lines (36 loc) · 1.08 KB
/
Merge Point of Two Linked Lists.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
/*
Time Complexity :- O(N)
Space Complexity :- O(1)
Where N is the maximum length of linked list.
*/
public class Solution {
private static int length(LinkedListNode<Integer> head) {
int length = 0;
while (head != null) {
head = head.next;
length++;
}
return length;
}
public static int findIntersection(LinkedListNode<Integer> firstHead, LinkedListNode<Integer> secondHead) {
// get the length of both list
int firstListLength = length(firstHead), secondListLength = length(secondHead);
// move headA and headB to the same start point
while (firstListLength > secondListLength) {
firstHead = firstHead.next;
firstListLength--;
}
while (firstListLength < secondListLength) {
secondHead = secondHead.next;
secondListLength--;
}
// find the intersection until end
while (firstHead != secondHead) {
firstHead = firstHead.next;
secondHead = secondHead.next;
}
if(firstHead == null)
return -1;
return firstHead.data;
}
}