mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 12:15:58 +08:00
Update 0142.环形链表II.md
This commit is contained in:
@ -221,25 +221,55 @@ public class Solution {
|
|||||||
Python:
|
Python:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
(版本一)快慢指针法
|
||||||
|
# Definition for singly-linked list.
|
||||||
|
# class ListNode:
|
||||||
|
# def __init__(self, x):
|
||||||
|
# self.val = x
|
||||||
|
# self.next = None
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def detectCycle(self, head: ListNode) -> ListNode:
|
def detectCycle(self, head: ListNode) -> ListNode:
|
||||||
slow, fast = head, head
|
slow = head
|
||||||
|
fast = head
|
||||||
|
|
||||||
while fast and fast.next:
|
while fast and fast.next:
|
||||||
slow = slow.next
|
slow = slow.next
|
||||||
fast = fast.next.next
|
fast = fast.next.next
|
||||||
# 如果相遇
|
|
||||||
|
# If there is a cycle, the slow and fast pointers will eventually meet
|
||||||
if slow == fast:
|
if slow == fast:
|
||||||
p = head
|
# Move one of the pointers back to the start of the list
|
||||||
q = slow
|
slow = head
|
||||||
while p!=q:
|
while slow != fast:
|
||||||
p = p.next
|
slow = slow.next
|
||||||
q = q.next
|
fast = fast.next
|
||||||
#你也可以return q
|
return slow
|
||||||
return p
|
# If there is no cycle, return None
|
||||||
|
return None
|
||||||
|
```
|
||||||
|
```python
|
||||||
|
(版本二)集合法
|
||||||
|
# Definition for singly-linked list.
|
||||||
|
# class ListNode:
|
||||||
|
# def __init__(self, x):
|
||||||
|
# self.val = x
|
||||||
|
# self.next = None
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def detectCycle(self, head: ListNode) -> ListNode:
|
||||||
|
visited = set()
|
||||||
|
|
||||||
|
while head:
|
||||||
|
if head in visited:
|
||||||
|
return head
|
||||||
|
visited.add(head)
|
||||||
|
head = head.next
|
||||||
|
|
||||||
return None
|
return None
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
Reference in New Issue
Block a user