stack using linked list

 avatar
user_9350232
plain_text
9 months ago
1.1 kB
8
Indexable
#include <iostream>
using namespace std;

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

class Stack {
    Node* top;
public:
    Stack() { top = NULL; }

    void push(int val) {
        Node* newNode = new Node();
        newNode->data = val;
        newNode->next = top;
        top = newNode;
        cout << val << " pushed to stack.\n";
    }

    void pop() {
        if (top == NULL)
            cout << "Stack Underflow!\n";
        else {
            cout << top->data << " popped from stack.\n";
            Node* temp = top;
            top = top->next;
            delete temp;
        }
    }

    void display() {
        cout << "Stack: ";
        Node* temp = top;
        while (temp != NULL) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
};

int main() {
    Stack s;
    s.push(5);
    s.push(10);
    s.display();
    s.pop();
    s.display();

    cout << "\nTime Complexity: O(1)\nSpace Complexity: O(n)\n";
    return 0;
}
Editor is loading...
Leave a Comment