🔲 Stack in DSA
A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The element that is added last to the stack is the first one to be removed. Think of it like a stack of plates where the top plate is the first one to be taken out.
Basic Operations of Stack
The main operations of a stack include:
- Push: Adds an element to the top of the stack.
- Pop: Removes the element from the top of the stack.
- Peek (Top): Returns the top element of the stack without removing it.
- isEmpty: Checks whether the stack is empty.
- isFull: Checks if the stack is full (in case of a fixed-size stack).
Types of Stack
There are several types of stacks based on how the operations are performed:
- Array-Based Stack: A stack implemented using an array.
- Linked List-Based Stack: A stack implemented using a linked list.
Stack Implementation
A stack can be implemented using either an array or a linked list. Here's an example of a stack implementation using an array:
#include
#define MAX 5
int stack[MAX];
int top = -1;
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = value;
printf("Pushed %d\n", value);
}
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int popped = stack[top];
top--;
return popped;
}
}
int peek() {
if (top == -1) {
printf("Stack is Empty\n");
return -1;
} else {
return stack[top];
}
}
int isEmpty() {
return (top == -1);
}
int main() {
push(10);
push(20);
push(30);
printf("Popped: %d\n", pop());
printf("Top: %d\n", peek());
return 0;
}
Applications of Stack
Stacks have many important applications in computer science, including:
- Expression Evaluation: Stacks are used to evaluate postfix or prefix expressions.
- Function Call Stack: The operating system uses a stack to manage function calls, storing return addresses and local variables.
- Undo/Redo Functionality: Many applications use stacks to implement undo/redo operations.
- Backtracking Algorithms: In problems like maze traversal or pathfinding, stacks are used for backtracking.
🚀 Advantages of Stacks:
- Fast and efficient for both push and pop operations.
- Ideal for problems involving recursion or backtracking.
- Simple and effective way to store temporary data.
🚀 Try Implementing Stack Operations:
- Implement a stack using a linked list and observe the differences from the array-based implementation.
- Experiment with an expression evaluator using stacks to process postfix or infix expressions.
- Create a function to reverse a string using stack operations.