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