Stack Data Structure in C (Complete Guide with Examples)
This tutorial explains the Stack data structure in C, a Last-In-First-Out (LIFO) structure. It covers concepts, operations (push, pop, peek), array and linked list implementations, and practical examples to improve problem-solving skills.
1. What is a Stack
- A stack is a linear data structure that follows LIFO (Last-In-First-Out) principle
- Last element inserted is the first one to be removed
- Common examples: browser history, undo feature, function call stack
2. Stack Operations
| OperationDescription |
push() | Insert element at top of stack |
pop() | Remove element from top of stack |
peek() | Get top element without removing |
isEmpty() | Check if stack is empty |
isFull() | Check if stack is full (for array implementation) |
3. Stack Implementation Using Array
#include <stdio.h>
#define MAX 5
int stack[MAX];
int top = -1;
void push(int x) {
if(top == MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = x;
printf("%d pushed to stack\n", x);
}
}
void pop() {
if(top == -1) {
printf("Stack Underflow\n");
} else {
printf("%d popped from stack\n", stack[top--]);
}
}
void peek() {
if(top == -1) {
printf("Stack is empty\n");
} else {
printf("Top element: %d\n", stack[top]);
}
}
int main() {
push(10);
push(20);
push(30);
peek();
pop();
peek();
return 0;
}
Sample Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
Top element: 30
30 popped from stack
Top element: 20
4. Stack Implementation Using Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Node *top = NULL;
void push(int x) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = top;
top = newNode;
printf("%d pushed to stack\n", x);
}
void pop() {
if(top == NULL) {
printf("Stack Underflow\n");
return;
}
struct Node *temp = top;
top = top->next;
printf("%d popped from stack\n", temp->data);
free(temp);
}
void peek() {
if(top == NULL) {
printf("Stack is empty\n");
} else {
printf("Top element: %d\n", top->data);
}
}
int main() {
push(10);
push(20);
push(30);
peek();
pop();
peek();
return 0;
}
Sample Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
Top element: 30
30 popped from stack
Top element: 20
5. Key Points to Remember
- Stack follows LIFO principle
- Can be implemented using arrays or linked lists
- Operations:
push, pop, peek, isEmpty, isFull - Array-based stack has fixed size, linked-list stack is dynamic
- Useful in function calls, recursion, expression evaluation, undo mechanisms