Open In App

Implement a stack using singly linked list

Last Updated : 20 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

To implement a stack using a singly linked list, we need to ensure that all operations follow the LIFO (Last In, First Out) principle. This means that the most recently added element is always the first one to be removed. In this approach, we use a singly linked list, where each node contains data and a reference (or link) to the next node.

To manage the stack, we maintain a top pointer that always points to the most recent (topmost) node in the stack. The key stack operations—push, pop, and peek can be performed using this top pointer.

In the stack Implementation, a stack contains a top pointer. which is the “head” of the stack where pushing and popping items happens at the head of the list. The first node has a null in the link field and second node-link has the first node address in the link field and so on and the last node address is in the “top” pointer.

The main advantage of using a linked list over arrays is that it is possible to implement a stack that can shrink or grow as much as needed. Using an array will put a restriction on the maximum capacity of the array which can lead to stack overflow. Here each new node will be dynamically allocated. so overflow is not possible.

Stack Operations

  • push(): Insert a new element into the stack (i.e just insert a new element at the beginning of the linked list.)
  • pop(): Return the top element of the Stack (i.e simply delete the first element from the linked list.)
  • peek(): Return the top element.
  • display(): Print all elements in Stack.

Push Operation

  • Initialise a node
  • Update the value of that node by data i.e. node->data = data
  • Now link this node to the top of the linked list
  • And update top pointer to the current node

Pop Operation

  • First Check whether there is any node present in the linked list or not, if not then return
  • Otherwise make pointer let say temp to the top node and move forward the top node by 1 step
  • Now free this temp node

Peek Operation

  • Check if there is any node present or not, if not then return.
  • Otherwise return the value of top node of the linked list

Display Operation

  • Take a temp node and initialize it with top pointer 
  • Now start traversing temp till it encounters NULL
  • Simultaneously print the value of the temp node
C++
#include <bits/stdc++.h>
using namespace std;

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

class Stack {
    Node* head;

public:
    Stack() { this->head = nullptr; }

    bool isEmpty() {
        return head == nullptr;
    }

    void push(int new_data) {
        Node* new_node = new Node(new_data);
        if (!new_node) {
            cout << "\nStack Overflow";
        }
        new_node->next = head;
        head = new_node;
    }

    void pop() {
        if (this->isEmpty()) {
            cout << "\nStack Underflow" << endl;
        } else {
            Node* temp = head;
            head = head->next;
            delete temp;
        }
    }

    int peek() {
        if (!isEmpty())
            return head->data;
        else {
            cout << "\nStack is empty";
            return INT_MIN;
        }
    }
};

int main() {
    Stack st;

    st.push(11);
    st.push(22);
    st.push(33);
    st.push(44);

    cout << "Top element is " << st.peek() << endl;

    cout << "Removing two elements..." << endl;
    st.pop();
    st.pop();

    cout << "Top element is " << st.peek() << endl;

    return 0;
}
C Java Python C# JavaScript

Output
Top element is 44
Removing two elements...
Top element is 22

Time Complexity: O(1), for all push(), pop(), and peek(), as we are not performing any kind of traversal over the list.
Auxiliary Space: O(n), where n is the size of the stack

Benefits of implementing a stack using a singly linked list

  • Dynamic memory allocation: The size of the stack can be increased or decreased dynamically by adding or removing nodes from the linked list, without the need to allocate a fixed amount of memory for the stack upfront.
  • Efficient memory usage: Since nodes in a singly linked list only have a next pointer and not a prev pointer, they use less memory than nodes in a doubly linked list.
  • Easy implementation: Implementing a stack using a singly linked list is straightforward and can be done using just a few lines of code.
  • Versatile: Singly linked lists can be used to implement other data structures such as queues, linked lists, and trees.

Real time examples of stack

Stacks are used in various real-world scenarios where a last-in, first-out (LIFO) data structure is required. Here are some examples of real-time applications of stacks:

  • Function Call Stack: When a function is called, its return address and parameters are pushed onto the stack. The stack ensures functions execute and return in reverse order..
  • Undo/Redo Operations: In apps like text or image editors, actions are pushed onto a stack. Undo removes the last action, while redo restores it.
  • Browser History: Browsers use stacks to track visited pages. Visiting a page pushes its URL onto the stack, and the “Back” button pops the last URL to go to the previous page.
  • Expression Evaluation: In compilers, expressions are converted to postfix notation and evaluated using a stack.
  • Call Stack in Recursion: Recursive function calls are pushed onto the stack. Once recursion ends, the stack is popped to return to the previous function call.


Next Article

Similar Reads

three90RightbarBannerImg