Consider the following Python code that checks if a linked list is circular. What will it print?
class Node: def __init__(self, val): self.val = val self.next = None def is_circular(head): if not head: return False slow = head fast = head.next while fast and fast.next: if slow == fast: return True slow = slow.next fast = fast.next.next return False # Create nodes node1 = Node(1) node2 = Node(2) node3 = Node(3) # Link nodes node1.next = node2 node2.next = node3 node3.next = node1 # Circular link print(is_circular(node1))
Think about how the fast and slow pointers move and when they meet.
The linked list is circular because node3 points back to node1. The fast and slow pointers will eventually meet, so the function returns True.
Given the code below, what will be the output?
class Node: def __init__(self, val): self.val = val self.next = None def is_circular(head): if not head: return False slow = head fast = head.next while fast and fast.next: if slow == fast: return True slow = slow.next fast = fast.next.next return False # Create nodes node1 = Node(1) node2 = Node(2) node3 = Node(3) # Link nodes node1.next = node2 node2.next = node3 node3.next = None # No circular link print(is_circular(node1))
Check if the fast pointer reaches the end of the list.
The list ends with node3.next = None, so fast pointer reaches None and the function returns False.
Identify the error in the following code that tries to detect if a linked list is circular.
class Node: def __init__(self, val): self.val = val self.next = None def is_circular(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False
Think about when the slow and fast pointers meet in a cycle.
The check should be if slow and fast point to the same node, not their next nodes.
Choose the best explanation for why Floyd's cycle detection algorithm uses a slow pointer and a fast pointer.
Think about how the pointers meet if a cycle exists.
The fast pointer moves twice as fast and will eventually catch up to the slow pointer if a cycle exists.
Analyze the code below and determine what it prints.
class Node: def __init__(self, val): self.val = val self.next = None def is_circular(head): if not head: return False slow = head fast = head.next while fast and fast.next: if slow == fast: return True slow = slow.next fast = fast.next.next return False # Single node circular list node1 = Node(1) node1.next = node1 print(is_circular(node1))
Consider how the fast and slow pointers start and move in a single node circular list.
The single node points to itself, so the fast pointer starts at node1.next which is node1, equal to slow, so returns True immediately.