Mental Model
A stack is like a pile where you add new items only on top. Pushing means placing a new item on the top of this pile.
Analogy: Imagine a stack of plates. When you add a new plate, you always put it on the top of the stack.
Top -> null
Top -> null
Top -> [1] -> null
Top -> [2] -> [1] -> null
Top -> [3] -> [2] -> [1] -> null
Top -> 3 -> 2 -> 1 -> null
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.top = None def push(self, value): new_node = Node(value) # create new node with value new_node.next = self.top # new node points to current top self.top = new_node # update top to new node def __str__(self): result = [] current = self.top while current: result.append(str(current.value)) current = current.next return ' -> '.join(result) + ' -> null' # Driver code stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack)
new_node = Node(value) # create new node with valuenew_node.next = self.top # new node points to current topself.top = new_node # update top to new nodeself.top = new_node # update top to new node