Skip to content
This repository was archived by the owner on Sep 22, 2021. It is now read-only.
This repository was archived by the owner on Sep 22, 2021. It is now read-only.

0141 - Linked List Cycle #304

@FergusYip

Description

@FergusYip

Description of the Problem

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Follow up:
Can you solve it using O(1) (i.e. constant) memory?

Code

class Solution:
    '''
    Solution using Floyd's cycle-finding algorithm (tortoise and hare)
    '''

    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next:
            return False

        fast = slow = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            # If there is a cycle, fast will inevitably be on the same node as
            # slow.
            if fast is slow:
                return True

        return False


class SolutionO1:
    '''
    Solution to follow up. Disregards contents of each ListNode.
    '''

    def hasCycle(self, head: ListNode) -> bool:
        while head:
            if head.val is None:
                return True
            head.val = None
            head = head.next
        return False

Link To The LeetCode Problem

LeetCode

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions