-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path160. Intersection of Two Linked Lists.java
58 lines (46 loc) · 1.31 KB
/
160. Intersection 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
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
return this.IntersectionNodeInTwoLL(headA, headB) ;
}
public ListNode IntersectionNodeInTwoLL(ListNode headA, ListNode headB) {
int n = getLength(headA);
int m = getLength(headB);
int diff = Math.abs(n - m);
ListNode intersectionPoint = null;
if (n > m) {
intersectionPoint = getIntersection(headA, headB, diff);
} else {
intersectionPoint = getIntersection(headB, headA, diff);
}
return intersectionPoint;
}
private ListNode getIntersection(ListNode headA, ListNode headB, int diff) {
ListNode slow = headB;
ListNode fast = headA;
for (int i = 0; i < diff; i++) fast = fast.next;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
private static int getLength(ListNode node) {
int len = 0;
while (node != null) {
node = node.next;
len++;
}
return len;
}
}