Poison

160. Intersection of Two Linked Lists

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode nodeA = headA, nodeB = headB;
while (nodeA != nodeB) {
nodeA = nodeA != null ? nodeA.next : headB;
nodeB = nodeB != null ? nodeB.next : headA;
}

return nodeA;
}
}

此题关键点在于判断是否为空时需要判断 node 而不是 node.next,如果判断 node.next 会在两个链表没有相交的情况下死循环,比如 [1, 2, 3][4, 5, 6] 这两个链表,判断 node 是否为空就能走到空节点而跳出循环。

Reference

160. Intersection of Two Linked Lists
剑指 Offer 52. 两个链表的第一个公共节点
剑指 Offer II 023. 两个链表的第一个重合节点