Stack is Empty.

Understanding the Stack Data Structure
A comprehensive overview of stacks, their operations, and real-world applications.
What is a Stack?
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. Elements are added and removed from the top of the stack.
Stack Operations
- Push: Adds an element to the top of the stack.
- Pop: Removes the top element from the stack.
- Peek: Returns the top element without removing it.
- isEmpty: Checks if the stack is empty.
- isFull: Checks if the stack is full (in case of a bounded stack).
Examples of Stack in Action
Some common examples of stack usage:
- Undo functionality in text editors.
- Backtracking in maze solving algorithms.
- Function call stack in programming.
Real-World Applications
Stacks are widely used in various computing contexts:
- Browser history navigation.
- Expression evaluation and syntax parsing.
- Managing recursive function calls.
Stack Code Implementation
// C code for Stack Implementation
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct Stack {
int items[MAX];
int top;
};
void initStack(struct Stack* stack) {
stack->top = -1;
}
int isFull(struct Stack* stack) {
return stack->top == MAX - 1;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
void push(struct Stack* stack, int element) {
if (isFull(stack)) {
printf("Stack Overflow\n");
} else {
stack->items[++stack->top] = element;
}
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
} else {
return stack->items[stack->top--];
}
}
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
} else {
return stack->items[stack->top];
}
}
int main() {
struct Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
printf("Top element: %d\n", peek(&stack));
pop(&stack);
printf("Top element after pop: %d\n", peek(&stack));
return 0;
}