Tuesday, 6 October 2026

C++ program to implement a Dynamic Stack using Pointer and Linked List.

 

#include <iostream>

using namespace std;

 

// Structure for a Node

struct Node {

    int data;       // Stores the value

    Node* next;     // Stores the address of the next node

};

 

// Top pointer of the stack

Node* top = NULL;

 

// Push operation

void push(int value) {

   

    // Create a new node

    Node* newNode = new Node;

 

    // Store the value

    newNode->data = value;

 

    // Connect new node to the current top

    newNode->next = top;

 

    // Make new node the new top

    top = newNode;

 

    cout << value << " pushed into stack" << endl;

}

 

// Pop operation

void pop() {

   

    // Check if stack is empty

    if (top == NULL) {

        cout << "Stack is empty" << endl;

        return;

    }

 

    // Store the top node temporarily

    Node* temp = top;

 

    // Display the value being removed

    cout << temp->data << " popped from stack" << endl;

 

    // Move top to the next node

    top = top->next;

 

    // Delete the old top node

    delete temp;

}

 

 

// Display stack

void display() {

   

    // Check if stack is empty

    if (top == NULL) {

        cout << "Stack is empty" << endl;

        return;

    }

 

    // Start from the top

    Node* temp = top;

 

    cout << "Stack: ";

 

    // Display all nodes

    while (temp != NULL) {

        cout << temp->data << " ";

        temp = temp->next;

    }

 

    cout << endl;

}

 

int main() {

 

    // Push elements

    push(10);

    push(20);

    push(30);

 

    display();

 

    pop();

 

    display();

 

    return 0;

}