-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path160_Intersection of Two Linked Lists
57 lines (47 loc) · 1.29 KB
/
160_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
57
/*
160. Intersection of Two Linked Lists
Runtime: 1 ms, faster than 99.36% of Java online submissions for Intersection of Two Linked Lists.
Memory Usage: 52.9 MB, less than 22.73% of Java online submissions for Intersection of Two Linked Lists.
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode test1=headA;
ListNode test2=headB;
if(headA==null || headB==null)
return null;
int l1=0,l2=0;
while(test1!=null)
{
test1=test1.next;
l1++;
}
while(test2!=null)
{
test2=test2.next;
l2++;
}
test1=headA;
test2=headB;
int diff=Math.abs(l1-l2);
if(l1>l2)
while(diff!=0)
{
test1=test1.next;
diff--;
}
if(l2>l1)
while(diff!=0)
{
test2=test2.next;
diff--;
}
while(test1!=null || test2!=null)
{
if(test1==test2)
return test1;
test1=test1.next;
test2=test2.next;
}
return null;
}
}