mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update 0142.环形链表II.md
This commit is contained in:
@ -221,25 +221,55 @@ public class Solution {
|
||||
Python:
|
||||
|
||||
```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:
|
||||
slow, fast = head, head
|
||||
slow = head
|
||||
fast = head
|
||||
|
||||
while fast and fast.next:
|
||||
slow = slow.next
|
||||
fast = fast.next.next
|
||||
# 如果相遇
|
||||
|
||||
# If there is a cycle, the slow and fast pointers will eventually meet
|
||||
if slow == fast:
|
||||
p = head
|
||||
q = slow
|
||||
while p!=q:
|
||||
p = p.next
|
||||
q = q.next
|
||||
#你也可以return q
|
||||
return p
|
||||
|
||||
# Move one of the pointers back to the start of the list
|
||||
slow = head
|
||||
while slow != fast:
|
||||
slow = slow.next
|
||||
fast = fast.next
|
||||
return slow
|
||||
# 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
|
||||
```
|
||||
Go:
|
||||
|
||||
```go
|
||||
|
Reference in New Issue
Block a user