Skip to main content

Stack Using Linked List (DSA)

Updated 2 min readMarkdown
Part of seriesDSA

A stack is one of the most fundamental linear data structures that follows the LIFO (Last In, First Out) principle. Implementing a stack using a linked list allows it to grow and shrink dynamically without a fixed size limit, where insertions and deletions happen at the top of the stack.

Stack Implementation in C++

#include <iostream>
using namespace std;

class Node{
    public:
    int data;
    Node* next;
    Node(int data){
        this->data = data;
        next = nullptr;
    }
};

class Stack{
    public:
    Node* top;
    int size;
    Stack(){
        top = nullptr;
        size = 0;
    }
    
    void insert(int data){
        Node* newNode = new Node(data);
        if(top == nullptr){
            top = newNode;
        }else{
            newNode->next = top;
            top = newNode;
            size++;
        }
    }

    void peek(){
        if(top == nullptr){
            cout<<"This Stack is Empty";
        }else{
            cout<<top->data<<endl;
        }
    }

    int pop(){
        if(top != nullptr){
            size--;
            int val = top->data;
            top = top->next;
            return val;
        }else{
            return 0;
        }
    }

    bool isEmpty(){
        if(top != nullptr){
            return false;
        }else{
            return true;
        }
    }

    void length(){
        cout<<size<<endl;
    }

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

int main(){
    Stack st;
    st.insert(10);
    st.insert(20);
    st.insert(30);
    st.insert(40);
    st.display();
    cout<<"----------"<<endl;
    st.pop();
    cout<<"element deleted"<<endl;
    st.display();
    // cout<<boola<<endl;
    cout<<boolalpha<<st.isEmpty()<<endl;
    cout<<"peek Value: ";
    st.peek();
    cout<<endl;
}

Output

40
30
20
10
----------
element deleted
30
20
10
false
peek Value: 30

About the author

No comments yet. Be the first to comment.