美文网首页
[leetcode]141. Linked List Cycle

[leetcode]141. Linked List Cycle

作者: SQUA2E | 来源:发表于2019-07-27 15:41 被阅读0次

题目

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

      本文链接:https://www.haomeiwen.com/subject/xljerctx.html