To implement a stack using a singly linked list, we represent the stack as a linked list whose head node is treated as the top of the stack. All stack operations-LIFO (last in, first out) behaviour-are implemented by manipulating the list at its head. In this approach, push and pop operate at the beginning of the linked list so each operation runs in constant time.



In this representation, a top pointer refers to the first node of the linked list. Each node contains a data field and a link (pointer) to the next node. The last node in the list has its link set to NULL. The principal advantage of using a linked list over a fixed-size array is dynamic size: nodes are allocated on the heap as needed, so the stack grows and shrinks at runtime without a static maximum capacity. Array-based stacks impose an upper bound and risk overflow; a linked-list stack can only overflow when the system runs out of memory.
A typical node for a singly linked list based stack contains two fields:
The stack maintains a single pointer top that refers to the first node. If top is NULL, the stack is empty.
The following C++ program demonstrates a simple, clear implementation of a stack using a singly linked list. The implementation uses new and delete for dynamic allocation and deallocation.
#include <iostream> #include <cstdlib> using namespace std; class Node { public: int data; Node* link; Node(int n) : data(n), link(nullptr) { } }; class Stack { Node* top; public: Stack() : top(nullptr) { } void push(int data) { Node* temp = new (nothrow) Node(data); if (temp == nullptr) { cout << "
Heap allocation failed: Stack Overflow" << endl; exit(EXIT_FAILURE); } temp->link = top; top = temp; } bool isEmpty() const { return top == nullptr; } int peek() const { if (!isEmpty()) return top->data; cout << "
Stack is empty: cannot perform peek" << endl; exit(EXIT_FAILURE); } void pop() { if (top == nullptr) { cout << "
Stack Underflow" << endl; exit(EXIT_FAILURE); } Node* temp = top; top = top->link; delete temp; } void display() const { if (top == nullptr) { cout << "
Stack is empty" << endl; return; } Node* temp = top; while (temp != nullptr) { cout << temp->data; temp = temp->link; if (temp != nullptr) cout << " -> "; } cout << endl; } }; int main() { Stack s; s.push(11); s.push(22); s.push(33); s.push(44); s.display(); cout << "Top element is " << s.peek() << endl; s.pop(); s.pop(); s.display(); cout << "Top element is " << s.peek() << endl; return 0; }
44 -> 33 -> 22 -> 11 Top element is 44 22 -> 11 Top element is 22
![]() | Explore Courses for Computer Science Engineering (CSE) exam |
![]() | Get EduRev Notes directly in your Google search |