LeetCode: Intersection of Two Linked Lists

LeetCode: 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

/**
* Created by hzhou on 4/22/15. [email protected]
*/
public class IntersectionOfTwoLinkedLists {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode cursor = headA;
int la = 0;
int lb = 0;
while (cursor != null) {
la++;
cursor = cursor.next;
}
cursor = headB;
while (cursor != null) {
lb++;
cursor = cursor.next;
}
ListNode ca = headA;
ListNode cb = headB;
if (la > lb) {
int tmp = la - lb;
while (tmp-- > 0) {
ca = ca.next;
}
} else {
int tmp = lb - la;
while (tmp-- > 0) {
cb = cb.next;
}
}
while (ca != null) {
if (ca == cb) {
return ca;
} else {
ca = ca.next;
cb = cb.next;
}
}
return null;
}
}