[leetcode]141. Linked List Cycle

题目

Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

分析

这道题目的是判断单链表中是否存在环,题目也额外要求了不用额外的空间。也就是说我们没法另外记录是否某个节点已经被访问过了。所以,这里使用了两个指针:快指针和慢指针。 如果单链表存在环, 那么快指针和慢指针最终会相遇。而如果快指针抵达了链表尾,那一定不存在环。

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = head
        fast = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True
        return False 

你可能感兴趣的:([leetcode]141. Linked List Cycle)