mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 面试题02.07.链表相交.md
This commit is contained in:
@ -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):
|
||||
|
Reference in New Issue
Block a user