[勇者闯LeetCode] 142. Linked List Cycle II

来源:互联网 发布:illustrator软件下载 编辑:程序博客网 时间:2024/06/05 15:36

[勇者闯LeetCode] 142. Linked List Cycle II

Description

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Information

  • Tags: Linked List | Two Pointers
  • Difficulty: Medium

Solution

使用快慢指针fast和slow从链头开始扫描,fast每次走两步,slow每次走一步,当fast与slow相遇时说明有环,此时将fast重新从链头开始扫描,且将扫描步长改为一步,那么可证明,当fast和slow两次相遇时,它们所指向的就是环的起点。

Python Code

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def detectCycle(self, head):        """        :type head: ListNode        :rtype: ListNode        """        fast, slow = head, head        while fast and fast.next:            fast, slow = fast.next.next, slow.next            if fast is slow:                fast = head                while fast is not slow:                    fast, slow = fast.next, slow.next                return fast        return None
原创粉丝点击