diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index d0967b8b..e2905d49 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -105,6 +105,7 @@ public: ### Java: ```Java +(版本一)先行移动长链表实现同步移动 public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode curA = headA; @@ -149,6 +150,23 @@ public class Solution { } } + +(版本二) 合并链表实现同步移动 +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + // p1 指向 A 链表头结点,p2 指向 B 链表头结点 + ListNode p1 = headA, p2 = headB; + while (p1 != p2) { + // p1 走一步,如果走到 A 链表末尾,转到 B 链表 + if (p1 == null) p1 = headB; + else p1 = p1.next; + // p2 走一步,如果走到 B 链表末尾,转到 A 链表 + if (p2 == null) p2 = headA; + else p2 = p2.next; + } + return p1; + } +} ``` ### Python: