Bird
0
0
DSA Cprogramming

Push Operation on Stack in DSA C

Choose your learning style9 modes available
Mental Model
A stack is like a pile where you add items only on top. Pushing means putting a new item on the top of this pile.
Analogy: Imagine a stack of plates. When you add a new plate, you always place it on the top of the stack.
Top -> null
Stack: null
Dry Run Walkthrough
Input: Start with empty stack, push values 10, then 20, then 30
Goal: Add each new value on top of the stack so the last pushed is on top
Step 1: Push 10 onto empty stack
Top -> [10] -> null
Why: First item becomes the top of the stack
Step 2: Push 20 onto stack
Top -> [20] -> [10] -> null
Why: New item goes on top, points to previous top
Step 3: Push 30 onto stack
Top -> [30] -> [20] -> [10] -> null
Why: Keep adding new items on top, linking to old top
Result:
Top -> [30] -> [20] -> [10] -> null
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

// Node structure for stack
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// Push function to add element on top
void push(Node** top_ref, int value) {
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->data = value;
    new_node->next = *top_ref; // link new node to current top
    *top_ref = new_node;       // update top to new node
}

// Print stack from top to bottom
void printStack(Node* top) {
    Node* current = top;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("null\n");
}

int main() {
    Node* stackTop = NULL; // empty stack

    push(&stackTop, 10);
    push(&stackTop, 20);
    push(&stackTop, 30);

    printStack(stackTop);
    return 0;
}
new_node->next = *top_ref; // link new node to current top
link new node to current top to keep stack order
*top_ref = new_node; // update top to new node
update top pointer to new node to make it the new top
OutputSuccess
30 -> 20 -> 10 -> null
Complexity Analysis
Time: O(1) because push adds one node at the top without traversing
Space: O(1) because only one new node is created per push
vs Alternative: Compared to array push which may require resizing, linked list push is always O(1) without shifting
Edge Cases
Empty stack
Push creates first node and sets it as top
DSA C
*top_ref = new_node;       // update top to new node
When to Use This Pattern
When you see a problem needing last-in-first-out order, reach for stack push because it adds elements on top efficiently.
Common Mistakes
Mistake: Not linking new node's next to current top before updating top
Fix: Always set new_node->next = *top_ref before changing *top_ref
Summary
Adds a new element on top of the stack.
Use when you want to store items in last-in-first-out order.
The new item always points to the old top, then becomes the new top.