-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersection_linkedlists.java
More file actions
41 lines (38 loc) · 943 Bytes
/
Copy pathintersection_linkedlists.java
File metadata and controls
41 lines (38 loc) · 943 Bytes
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
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
ListNode ptrA = headA;
ListNode ptrB = headB;
int lenA = 1;
int lenB = 1;
while(ptrA!=null){
ptrA = ptrA.next;
lenA++;
}
while(ptrB!=null){
ptrB = ptrB.next;
lenB++;
}
ptrA = headA;
ptrB = headB;
int diff = Math.abs(lenA-lenB);
if(lenA>lenB){
while(diff>0){
ptrA = ptrA.next;
diff--;
}
}
else if(lenA<lenB){
while(diff>0){
ptrB = ptrB.next;
diff--;
}
}
while(ptrA!=ptrB){
ptrA = ptrA.next;
ptrB = ptrB.next;
}
return ptrA;
}
}