Skip to main content

#141. Linked List Cycle | LeetCode Python Solution

Problem

LeetCode Problem

  1. Linked List Cycle

Python Solution

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# No cycle if the list is empty
if head is None:
return False

# Use a set to keep track of memory location of visited nodes
node_set = set()

c = head
while c.next is not None:
# Cycle detected if the 'next' pointer references the memory location of visited nodes
if c.next in node_set:
return True

# Add current node's memory location to the set
node_set.add(c)

# Advance current pointer to next node
c = c.next

# Reached the end of the given linked list without detecting any cycle
return False