Update 0142.环形链表II.md

This commit is contained in:
jianghongcheng
2023-05-03 17:27:27 -05:00
committed by GitHub
parent e4072d9a00
commit b2bfb80166

View File

@ -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 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
```go ```go