Why Use Linked List for Stack?
Unlike arrays, a stack implemented with a linked list does not have a fixed size and can grow or shrink as needed during runtime. This makes it more memory efficient.
Stack Operations
Operation | Description |
---|---|
PUSH | Insert an element at the top of the stack |
POP | Remove the top element from the stack |
DISPLAY | View the stack from top to bottom |
C Program: Stack Using Linked List
#include <stdio.h>
#include <stdlib.h>
// Structure for a stack node
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
// PUSH operation
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed\n");
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
printf("%d pushed to stack\n", value);
}
// POP operation
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);
}
// DISPLAY operation
void display() {
if (top == NULL) {
printf("Stack is empty\n");
return;
}
struct Node* temp = top;
printf("Stack elements: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Main function
int main() {
int choice, value;
do {
printf("\nMenu:\n1. PUSH\n2. POP\n3. DISPLAY\n4. EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Exiting program...\n");
break;
default:
printf("Invalid choice. Try again.\n");
}
} while (choice != 4);
return 0;
}
Output Example
Menu:
1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice: 1
Enter value to push: 10
10 pushed to stack
Enter your choice: 1
Enter value to push: 20
20 pushed to stack
Enter your choice: 3
Stack elements: 20 -> 10 -> NULL
Enter your choice: 2
20 popped from stack
Enter your choice: 3
Stack elements: 10 -> NULL
Key Benefits of Linked List Stack
- No overflow unless system memory is full.
- Dynamic memory allocation.
- Efficient for applications requiring dynamic stacks (e.g., recursion tracking, undo functionality).