Consider the following Python code that pushes nodes to the front of a linked list. What will be the printed linked list after all push operations?
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while temp: print(temp.data, end=' -> ') temp = temp.next print('null') llist = LinkedList() llist.push(10) llist.push(20) llist.push(30) llist.printList()
Remember, push adds a new node at the front of the list.
Each push adds a new node at the beginning. So the last pushed node (30) becomes the head, followed by 20, then 10.
Given this code snippet, what will be the final linked list printed?
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while temp: print(temp.data, end=' -> ') temp = temp.next print('null') llist = LinkedList() llist.push(5) llist.push(15) llist.push(25) llist.push(35) llist.printList()
New nodes are added at the front, so the last pushed node is the head.
Push adds nodes at the front, so the list order is reversed from the push order.
Look at this push method in a linked list class. It causes an error when called. What is the cause?
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head.next
self.head = new_nodeThink about what happens if the list is empty before push.
If the list is empty, self.head is None. Accessing self.head.next causes an error because None has no attribute 'next'.
Given the following code, what will be the printed linked list?
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while temp: print(temp.data, end=' -> ') temp = temp.next print('null') llist = LinkedList() for value in [1, 2, 3, 4, 5]: llist.push(value) llist.printList()
Push adds each new node at the front, reversing the order.
The last pushed value (5) becomes the head, so the list is reversed from the input order.
Consider a singly linked list. What is the time complexity of the push operation that adds a node at the front?
Think about how many nodes you need to visit to add at the front.
Adding a node at the front only changes the head pointer and the new node's next pointer, which takes constant time.