-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path4. Intersection of Two Linked Lists
56 lines (49 loc) · 1.37 KB
/
4. Intersection of Two Linked Lists
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
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//Length of List A
int lenA=0;
ListNode tempA = headA;
while(tempA != null){
lenA++;
tempA = tempA.next;
}
//Length of B list
int lenB=0;
ListNode tempB = headB;
while(tempB != null){
lenB++;
tempB = tempB.next;
}
int diff = Math.abs(lenA-lenB);
//Iterate on larger list for diff nodes
tempA=headA;
tempB=headB;
if(lenA > lenB) {
while(diff-- > 0)
tempA = tempA.next;
}
else {
while(diff-- > 0)
tempB = tempB.next;
}
//Check for equality
while(tempA != tempB){
tempA = tempA.next;
tempB = tempB.next;
if(tempA == null || tempB == null)
return null;
}
return tempA;
}
}
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA != tempB) {
tempA = tempA != null ? tempA.next : headB;
tempB = tempB != null ? tempB.next : headA;
}
return tempA;
}
}