链表对齐之后再判断
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int n1 = 0, n2 = 0;
for (ListNode p = headA; p != null; p = p.next) {
n1++;
}
for (ListNode p = headB; p != null; p = p.next) {
n2++;
}
ListNode shortNode, LongNode;
int dif;
if (n1 > n2) {
dif = n1 - n2;
shortNode = headB;
LongNode = headA;
} else {
dif = n2 - n1;
shortNode = headA;
LongNode = headB;
}
for (int i = 0; i < dif; i++) {
LongNode = LongNode.next;
}
while (shortNode != null) {
if (shortNode == LongNode) {
return shortNode;
}
shortNode = shortNode.next;
LongNode = LongNode.next;
}
return null;
}
}
牛逼解法
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode h1 = headA, h2 = headB;
while (h1 != h2) {
h1 = (h1 == null) ? headB : h1.next;
h2 = (h2 == null) ? headA : h2.next;
}
return h1;
}
}
设交集链表长c,链表1除交集的长度为a,链表2除交集的长度为b,有
- a + c + b = b + c + a
- 若无交集,则a + b = b + a