From abc86e9a7d66851ada0e54f74efd50b9ce5da8f2 Mon Sep 17 00:00:00 2001 From: Heeqw <124508798+Heeqw@users.noreply.github.com> Date: Sat, 27 Jan 2024 17:05:04 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E9=9D=A2=E8=AF=95=E9=A2=9802.07.?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加了一种java语言的同步移动方法 --- problems/面试题02.07.链表相交.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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: