
HashSet
- 第一遍从遍历一遍A链表,遍历的节点存到Set集合中
- 第二遍遍历B链表,如果出现已经存在的节点,则直接返回,即为公共节点
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
ListNode p = headA;
while (p != null) {
set.add(p);
p = p.next;
}
p = headB;
while (p != null) {
if (set.contains(p)) {
return p;
}
p = p.next;
}
return null;
}
}
双指针
- 设公共节点为
node
- A链表长度为
a
- B链表长度为
b
node 到链表尾距离为 c
- 思路:让
pA 一直遍历到尾部,然后下一次的起点为 headB ;同时 pB 一直遍历到尾部,下一次的起点为 headA ,两者汇合之后,就在公共节点处。没交集,则两者最后都是 null.
- 证明:模拟上述过程:
a+(b−c)=b+(a−c)
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}
鸣谢:leetcode-cn.com/problems/in…