Stacks in C
After learning linked lists, we are now ready to study one of the most important data structures: the Stack.
Stacks are used everywhere in computer science, even when you run a program.
What Is a Stack?
A stack is a linear data structure that follows the principle:
LIFO – Last In, First Out
This means the element inserted last will be removed first.
Real-World Example
Think of a stack of plates:
- You place a plate on top
- You remove the top plate first
You cannot remove a plate from the middle.
Basic Stack Operations
- Push – Insert an element
- Pop – Remove the top element
- Peek – View the top element
Stack Implementation Using Array
This is the simplest way to understand stacks.
#include <stdio.h>
#define SIZE 5
int stack[SIZE];
int top = -1;
void push(int value) {
if (top == SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = value;
}
void pop() {
if (top == -1) {
printf("Stack Underflow\n");
return;
}
printf("Popped: %d\n", stack[top--]);
}
int main() {
push(10);
push(20);
push(30);
pop();
pop();
return 0;
}
Stack Overflow and Underflow
- Overflow – Stack is full, cannot push
- Underflow – Stack is empty, cannot pop
Stack Using Linked List
Linked list implementation removes size limitation.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Node *top = NULL;
void push(int value) {
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = top;
top = newNode;
}
void pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return;
}
struct Node *temp = top;
printf("Popped: %d\n", temp->data);
top = temp->next;
free(temp);
}
int main() {
push(5);
push(15);
pop();
pop();
return 0;
}
Where Stacks Are Used
- Function calls (call stack)
- Undo / Redo operations
- Expression evaluation
- Backtracking algorithms
Mini Practice
- Create a stack using array
- Implement push and pop
- Display top element
Quick Quiz
Q1. What does LIFO mean?
Last In, First Out
Q2. What operation inserts an element?
Push
Q3. What is stack overflow?
Trying to push into a full stack
Q4. Which stack implementation removes size limitation?
Linked list
Q5. Are stacks used in real programs?
Yes