From e4072d9a00b12c6de6949091378bdd8d95b5296c Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 17:25:36 -0500 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 --- problems/面试题02.07.链表相交.md | 63 ++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 30f5c467..4bcbd1f9 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -152,7 +152,7 @@ public class Solution { ### Python ```python - +(版本一)求长度,同时出发 class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lenA, lenB = 0, 0 @@ -178,7 +178,68 @@ class Solution: curB = curB.next return None ``` +```python +(版本二)求长度,同时出发 (代码复用) +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + lenA = self.getLength(headA) + lenB = self.getLength(headB) + + # 通过移动较长的链表,使两链表长度相等 + if lenA > lenB: + headA = self.moveForward(headA, lenA - lenB) + else: + headB = self.moveForward(headB, lenB - lenA) + + # 将两个头向前移动,直到它们相交 + while headA and headB: + if headA == headB: + return headA + headA = headA.next + headB = headB.next + + return None + + def getLength(self, head: ListNode) -> int: + length = 0 + while head: + length += 1 + head = head.next + return length + + def moveForward(self, head: ListNode, steps: int) -> ListNode: + while steps > 0: + head = head.next + steps -= 1 + return head +``` +```python +(版本三)等比例法 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + # 处理边缘情况 + if not headA or not headB: + return None + + # 在每个链表的头部初始化两个指针 + pointerA = headA + pointerB = headB + + # 遍历两个链表直到指针相交 + while pointerA != pointerB: + # 将指针向前移动一个节点 + pointerA = pointerA.next if pointerA else headB + pointerB = pointerB.next if pointerB else headA + + # 如果相交,指针将位于交点节点,如果没有交点,值为None + return pointerA +``` ### Go ```go