Stacks are simple yet powerful data structures widely used in everything from reversing words to handling function calls in programs. If the idea is new to you, imagine stacking plates: You can add a new plate only to the top, and you can only remove the topmost one. This is LIFO: Last In, First Out.
C Implementation
Let's use an array and a variable to represent a stack:
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1; // Empty stack
// Function prototypes
void push(int data);
int pop();
int isEmpty();
int isFull();
int main() {
// Example usage
push(10);
push(20);
push(30);
printf("Popped: %d\n", pop()); // Output: Popped: 30
if (!isEmpty()) {
printf("Top element: %d\n", stack[top]);
}
return 0;
}
// Stack operation functions
void push(int data) {
if (isFull()) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = data;
}
}
int pop() {
if (isEmpty()) {
printf("Stack Underflow\n");
return -1;
} else {
int data = stack[top];
top--;
return data;
}
}
int isEmpty() {
return top == -1;
}
int isFull() {
return top == MAX_SIZE - 1;
}
Explanations
Initialization: top is initialized to -1 indicating an empty stack.
push(data):
Checks if the stack is full; if so, indicates overflow.
Otherwise, increments top and inserts the data element.
pop():
Checks if the stack is empty; if so, indicates underflow.
Otherwise, retrieves the top element, decrements top, and returns the element.
isEmpty() and isFull(): Helper functions to check the stack's state.
*Key Points
Stacks follow LIFO order.
Stack operations are simple and efficient.
Real-world use cases include:
Undo/Redo functionality in editors
Expression evaluation
Backtracking algorithms
Comments