diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 46df4777..e80a715a 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -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