-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path160-Intersection_LinkedList.java
77 lines (65 loc) · 1.8 KB
/
160-Intersection_LinkedList.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
class LengthAndTail{
int length;
ListNode tail;
LengthAndTail(int length,ListNode tail){
this.length = length;
this.tail = tail;
}
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null)
return null;
LengthAndTail lengthA = getListLength(headA);
LengthAndTail lengthB = getListLength(headB);
if(lengthA.tail.val!=lengthB.tail.val)
return null;
int diff = 0;
if(lengthA.length>=lengthB.length){
diff = lengthA.length-lengthB.length;
int count =0;
while(count!=diff && headA.next!=null){
headA=headA.next;
count=count+1;
}
}
else{
diff = lengthB.length-lengthA.length;
int count =0;
while(count!=diff && headB.next!=null){
headB=headB.next;
count=count+1;
}
}
while(headA!=null){
if(headA==headB)
return headA;
else{
headA=headA.next;
headB=headB.next;
}
}
return null;
}
public LengthAndTail getListLength(ListNode head){
int length = 0;
ListNode tail = null;
while(head!=null){
length = length + 1;
tail = head;
head=head.next;
}
return new LengthAndTail(length,tail);
}
}