https://leetcode.com/problems/intersection-of-two-linked-lists/
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int off = off(headA, headB);
if (off >= 0) {
while (off-- > 0) {
headA = headA.next;
}
} else {
while (off++ < 0) {
headB = headB.next;
}
}
while (headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
// return off > 0, the first is longer, else the second is longer
private int off(ListNode a, ListNode b) {
while (a != null && b != null) {
a = a.next;
b = b.next;
}
int k = 0;
if (a != null) {
while (a != null) {
++k;
a = a.next;
}
return k;
} else {
while (b != null) {
++k;
b = b.next;
}
return -k;
}
}
}