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
版本一快慢指针法
# 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