TheHingineer

  • Data Structures & Algorithms


  • DSA Part-1

  • DSA Part-2

  • DSA Part-3

  • DSA Part-4

  • DSA Part-5

  • Stack Implementation using Linked List

    Array-based stack ka sabse bada drawback yeh hota hai ki iska size fixed hota hai. Agar array full ho jaye toh Stack Overflow hota hai aur agar array large declare karein toh memory waste hoti hai. Linked List based Stack ek dynamic stack hota hai jo runtime par memory grow ya shrink karta hai.

    Design Principle

    Linked list me TOP pointer hamesha list ke HEAD ko point karta hai:

    • Push Operation: Insertion at Beginning (Head) – O(1) time.
    • Pop Operation: Deletion from Beginning (Head) – O(1) time.
    TOP
     |
     v
    [ 30 | Next ] ---> [ 20 | Next ] ---> [ 10 | Next ] ---> NULL
    

    C Implementation

    struct Node {
        int data;
        struct Node* next;
    };
    struct Node* top = NULL;
    
    void push(int val) {
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        if (!newNode) { printf("Heap Overflow!\n"); return; }
        newNode->data = val;
        newNode->next = top;
        top = newNode;
    }
    
    int pop() {
        if (top == NULL) { printf("Stack Underflow!\n"); return -1; }
        struct Node* temp = top;
        int val = temp->data;
        top = top->next;
        free(temp);
        return val;
    }

    Agli post me hum cover karenge Infix, Prefix, and Postfix Notations.

    Scroll to Top