0
0
DSA Pythonprogramming

Push Operation on Stack in DSA Python

Choose your learning style9 modes available
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
Dry Run Walkthrough
Input: Start with empty stack, push values 1, then 2, then 3
Goal: Add each new value on top of the stack so the last pushed is on top
Step 1: Push 1 onto empty stack
Top -> [1] -> null
Why: First item becomes the top of the stack
Step 2: Push 2 onto stack
Top -> [2] -> [1] -> null
Why: New item goes on top, previous top moves down
Step 3: Push 3 onto stack
Top -> [3] -> [2] -> [1] -> null
Why: Keep adding new items on top, stack grows upwards
Result:
Top -> 3 -> 2 -> 1 -> null
Annotated Code
DSA Python
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 value
create a new node to hold the pushed value
new_node.next = self.top # new node points to current top
link new node to the current top node to keep stack chain
self.top = new_node # update top to new node
update stack top pointer to new node, making it the new top
OutputSuccess
3 -> 2 -> 1 -> null
Complexity Analysis
Time: O(1) because push adds one item on top without traversing
Space: O(1) extra space for the new node created during push
vs Alternative: Compared to array-based stack, linked list push avoids resizing and copying, always O(1)
Edge Cases
Empty stack
Push sets top to new node correctly
DSA Python
self.top = new_node  # update top to new node
When to Use This Pattern
When you need to add an item to a stack quickly and always on top, use the push operation to maintain last-in-first-out order.
Common Mistakes
Mistake: Forgetting to link the new node's next to the current top
Fix: Always set new_node.next = self.top before updating self.top
Mistake: Updating top before linking new node's next
Fix: Link new_node.next first, then update self.top to new_node
Summary
Push adds a new item on top of the stack.
Use push when you want to insert elements in last-in-first-out order.
The key is to link the new node to the current top before updating the top pointer.