Complete the code to create a circular linked list where the last node points back to the head.
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node new_node.next = [1] else: temp = self.head while temp.next != self.head: temp = temp.next temp.next = new_node new_node.next = self.head
In a circular linked list, the last node's next pointer must point back to the head node to form a circle.
Complete the code to traverse and print all nodes in a circular linked list exactly once.
def print_list(cll): if not cll.head: return temp = cll.head while True: print(temp.data, end=' -> ') temp = [1] if temp == cll.head: break print('null')
To move through the circular linked list, we update temp to temp.next at each step.
Fix the error in the code to correctly insert a new node after the head in a circular linked list.
def insert_after_head(cll, data): if not cll.head: cll.head = Node(data) cll.head.next = cll.head else: new_node = Node(data) new_node.next = cll.head.next cll.head.next = [1]
To insert after the head, the head's next pointer must point to the new node.
Fill both blanks to create a function that checks if a circular linked list contains a given value.
def contains(cll, value): if not cll.head: return False temp = cll.head while True: if temp.data == [1]: return [2] temp = temp.next if temp == cll.head: break return False
We compare each node's data with the value and return True if found.
Fill all three blanks to create a dictionary that maps each node's data to its next node's data in a circular linked list.
def map_to_next(cll): if not cll.head: return {} result = {} temp = cll.head while True: result[[1]] = [2] temp = [3] if temp == cll.head: break return result
The dictionary maps each node's data (key) to the next node's data (value). We use temp to iterate.