Which statement best describes the key difference between a circular linked list and a linear linked list?
Think about what happens when you reach the last node in each list type.
The main difference is how the last node connects. In a circular linked list, the last node links back to the first node, forming a loop. In a linear linked list, the last node points to null, marking the end.
What will be the output of the following code that traverses a circular linked list with 3 nodes?
class Node: def __init__(self, data): self.data = data self.next = None # Create nodes node1 = Node(1) node2 = Node(2) node3 = Node(3) # Link nodes in a circular way node1.next = node2 node2.next = node3 node3.next = node1 # Traverse starting from node1, print 5 nodes current = node1 count = 0 while count < 5: print(current.data, end=' -> ') current = current.next count += 1 print('null')
Remember the list loops back to the start after the last node.
The list has 3 nodes linked circularly. Traversing 5 nodes prints 1, 2, 3, then loops back to 1 and 2 again before stopping.
What will be the output of the following code that traverses a linear linked list with 3 nodes?
class Node: def __init__(self, data): self.data = data self.next = None # Create nodes node1 = Node(1) node2 = Node(2) node3 = Node(3) # Link nodes linearly node1.next = node2 node2.next = node3 node3.next = None # Traverse starting from node1, print all nodes current = node1 while current is not None: print(current.data, end=' -> ') current = current.next print('null')
In a linear linked list, the last node points to null.
The list has 3 nodes linked linearly. Traversing stops after the last node because its next is null.
What error will occur when running this code that tries to traverse a circular linked list without a stopping condition?
class Node: def __init__(self, data): self.data = data self.next = None node1 = Node(1) node2 = Node(2) node3 = Node(3) node1.next = node2 node2.next = node3 node3.next = node1 current = node1 while current is not None: print(current.data, end=' -> ') current = current.next # No stopping condition for circular list
Think about what happens when the list loops back to the start and there is no stop.
The loop never ends because current never becomes None in a circular linked list. It keeps cycling through nodes endlessly.
You want to design a music playlist that repeats songs endlessly without restarting manually. Which linked list type is best suited for this?
Think about which list type naturally repeats without extra code.
A circular linked list loops back to the first node, making it perfect for playlists that repeat endlessly without manual restart.