160. Intersection of Two Linked Lists
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3Last updated
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3Last updated
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode a = headA, b = headB;
while (a != b) {
a = (a == null ? headB : a.next);
b = (b == null ? headA : b.next);
}
return b;
}
}public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// get lengths first
int lenA = getListLength(headA);
int lenB = getListLength(headB);
// find diff
boolean aIsLonger = lenA - lenB > 0 ? true : false;
int diff = aIsLonger? lenA - lenB : lenB - lenA;
// move the head of the longer list to the place where lists have same length
ListNode currA = headA, currB = headB;
if (aIsLonger) {
while (diff != 0) {
currA = currA.next;
diff--;
}
} else {
while (diff != 0) {
currB = currB.next;
diff--;
}
}
// now both lists have the same length left
while (currA != null) {
if (currA == currB) return currA;
else {
currA = currA.next;
currB = currB.next;
}
}
// return null if cannot find a common node
return null;
}
private int getListLength(ListNode head) {
int len = 0;
while (head != null) {
len++;
head = head.next;
}
return len;
}