Linked List Cycle

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 integerposwhich represents the position (0-indexed)in the linked list where tail connects to. Ifposis-1, then there is no cycle in the linked list.

Example :

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.

题意: 给定一个链表,判断链表中是否有环。

# Author:kilien
# Leetcode 141.Linked List Cycle
# 思路1:使用set记录链表元素,重复即有环
# time:O(n) space:O(n)
class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        key = set()
        while head:
            if head in key:
                return True
            else:
                key.add(head)
            head = head.next
        return False


# 思路2:使用快慢指针,当两者相遇则有环
# time:O(n) space:O(1)
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

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

过程如图:

Last Updated: