Pages

Friday, July 4, 2025

Implementation of Stack using Linked LIst in C++

#include <iostream>
#include <cstdlib>
using namespace std;

struct Node {
    int data;
    Node* next;
};

Node* top = NULL; // Global stack top pointer

void linkedListTraversal(Node* ptr) {
    while (ptr) { // Fixed: Correct loop condition
        cout << "Element: " << ptr->data << endl;
        ptr = ptr->next;
    }
}

int isEmpty(Node* top) {
    return (!top);
}

int isFull(Node* top) {
    Node* p = (Node*) malloc(sizeof(Node));
    if (!p) {
        return 1; // Stack is full (memory can't be allocated)
    } else {
        free(p);
        return 0;
    }
}

Node* push(Node* top, int x) {
    Node* n = new Node;
    if (!n) {
        cout << "Stack Overflow" << endl;
        return top;
    }

    n->data = x;
    n->next = top;
    top = n;

    return top;
}

int pop() {
    if (isEmpty(top)) {
        cout << "Stack Underflow" << endl;
        return -1;
    } else {
        Node* n = top;
        int x = n->data;
        top = top->next;
        free(n); // You used malloc in isFull(), so free() is OK here
        return x;
    }
}

int main() {
    top = push(top, 78);
    top = push(top, 7);
    top = push(top, 8);

    int element = pop();
    cout << "Popped element: " << element << endl;

    linkedListTraversal(top);

    return 0;
}

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...