Update 面试题02.07.链表相交.md

This commit is contained in:
jianghongcheng 2023-05-05 19:18:26 -05:00 committed by GitHub
parent 3b0000a280
commit 4224c17e54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 35 additions and 1 deletions

View File

@ -214,7 +214,41 @@ class Solution:
return head
```
```python
(版本三)等比例法
(版本三)求长度,同时出发 (代码复用 + 精简)
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
dis = self.getLength(headA) - self.getLength(headB)
# 通过移动较长的链表,使两链表长度相等
if dis > 0:
headA = self.moveForward(headA, dis)
else:
headB = self.moveForward(headB, abs(dis))
# 将两个头向前移动,直到它们相交
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):