Stack Using Linked List in Data Structure
A Stack is a linear data structure that follows the LIFO (Last In First Out) principle. In a stack, the
element that is inserted last is the first to be deleted. Stack operations are performed mainly at one
end — called the top of the stack. Linked list implementation of stack uses pointers to dynamically
allocate memory for each stack element.
Basic Stack Operations:
1. push() – Insert an element into the stack.
2. pop() – Remove the top element from the stack.
3. peek() / top() – Return the top element without removing it.
4. isEmpty() – Check whether the stack is empty.
Algorithm for Stack using Linked List:
1. PUSH Operation:
Step 1: Create a new node.
Step 2: Set data to the new node.
Step 3: Point the new node's next to the current top.
Step 4: Move top pointer to the new node.
2. POP Operation:
Step 1: If top is NULL, Stack Underflow.
Step 2: Else, store the top node in a temp pointer.
Step 3: Move top to the next node.
Step 4: Delete temp node.
3. DISPLAY Operation:
Step 1: Start from top node.
Step 2: Traverse through all nodes until NULL.
Step 3: Print each node’s data.
Program in C:
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; };
struct Node* top = NULL; void push(int value) { struct Node* newNode = (struct
Node*)malloc(sizeof(struct Node)); newNode->data = value; newNode->next = top; top =
newNode; printf("%d pushed to stack\n", value); } void pop() { if (top == NULL) {
printf("Stack Underflow\n"); return; } struct Node* temp = top; printf("%d popped
from stack\n", top->data); top = top->next; free(temp); } void display() { struct
Node* temp = top; if (top == NULL) { printf("Stack is empty\n"); return; }
printf("Stack elements:\n"); while (temp != NULL) { printf("%d\n", temp->data); temp
= temp->next; } } int main() { push(10); push(20); push(30); display(); pop();
display(); return 0; }
Conclusion:
The linked list implementation of stack eliminates the limitation of fixed size. Memory is allocated
dynamically, and elements can grow or shrink during program execution.