Stack in C
A Stack is a linear data structure that follows the LIFO rule (Last In, First Out).
The element inserted last is removed first.
Stacks are widely used in memory handling, expression evaluation, recursion, and function calls.
What is a Stack?
A stack works like a pile of plates β the last plate placed is the first one removed. In C, stacks can be implemented using:
- Arrays
- Linked Lists
LIFO Rule
PUSH β PUSH β PUSH POP β POP β POP
Basic Stack Operations
- push() β Insert element
- pop() β Remove element
- peek() β View top element
- isEmpty() β Check if stack is empty
- isFull() β Check if stack is full
Stack Representation (Array)
Index: 0 1 2 3 4
Value: 5 9 3 8 -
β
TOP
Stack Implementation (Array)
Full Code Implementation
#include <stdio.h>
#define MAX 5
int stack[MAX];
int top = -1;
void push(int x){
if(top == MAX-1){
printf("Stack Overflow\n");
return;
}
stack[++top] = x;
}
int pop(){
if(top == -1){
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int peek(){
if(top == -1){
printf("Stack Empty\n");
return -1;
}
return stack[top];
}
void display(){
if(top == -1){
printf("Stack Empty\n");
return;
}
for(int i=top;i>=0;i--)
printf("%d ", stack[i]);
}
int main(){
push(10);
push(20);
push(30);
display();
return 0;
}
5 Practical Stack Examples (CopyβPaste)
Example 1 β Push & Pop
#include <stdio.h>
int stack[10], top=-1;
void push(int x){ stack[++top]=x; }
int pop(){ return stack[top--]; }
int main(){
push(5);
push(9);
printf("%d", pop());
return 0;
}
Example 2 β Peek Top Element
#include <stdio.h>
int stack[5], top=-1;
int peek(){
if(top==-1) return -1;
return stack[top];
}
int main(){
stack[++top] = 11;
stack[++top] = 22;
printf("%d", peek());
return 0;
}
Example 3 β Stack Underflow
#include <stdio.h>
int pop(int stack[], int *top){
if(*top==-1){
printf("Underflow");
return -1;
}
return stack[(*top)--];
}
int main(){
int s[5], top=-1;
pop(s, &top);
return 0;
}
Example 4 β Display Stack
#include <stdio.h>
int main(){
int stack[]={10,20,30}, top=2;
for(int i=top;i>=0;i--)
printf("%d ", stack[i]);
return 0;
}
Example 5 β Push Until Full
#include <stdio.h>
#define MAX 3
int main(){
int stack[MAX], top=-1;
for(int i=0;i<5;i++){
if(top==MAX-1) printf("Full\n");
else stack[++top]=i;
}
return 0;
}
Real Life Uses of Stack
- Undo/Redo operations
- Browser back button
- Expression evaluation
- Function call stack
- Memory management
Practice Questions
- Explain LIFO with real examples.
- Write stack operations using array.
- Difference between push() and pop().
- Implement stack using linked list.
- Explain function call stack.