STACK PROBLEM-SOLVING TRICKS IN C
Essential Stack Manipulation Tricks
| # | Trick | Description | Code Example |
|---|---|---|---|
| 1 | Array-based implementation | Simple stack using fixed-size array with top pointer. Efficient for known maximum size. |
#define MAX 100
int stack[MAX], top = -1; // Push operation void push(int item) { if (top == MAX-1) { printf("Stack overflow"); } else { stack[++top] = item; } } |
| 2 | Linked list implementation | Dynamic stack using linked nodes. No size limitation but slightly more memory overhead. |
struct Node {
int data; struct Node* next; }; struct Node* top = NULL; // Push operation void push(int item) { struct Node* newNode = malloc(sizeof(struct Node)); newNode->data = item; newNode->next = top; top = newNode; } |
| 3 | Double stack in single array | Two stacks growing from opposite ends of an array. Efficient space utilization. |
#define MAX 100
int arr[MAX]; int top1 = -1, top2 = MAX; // Push to stack1 void push1(int item) { if (top1 < top2-1) { arr[++top1] = item; } else { printf("Stack Overflow"); } } |
| 4 | Parentheses balancing | Check for matching parentheses, brackets, and braces in an expression. |
bool isBalanced(char* exp) {
char stack[MAX]; int top = -1; for (int i = 0; exp[i]; i++) { if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') { stack[++top] = exp[i]; } else if (exp[i] == ')') { if (top == -1 || stack[top--] != '(') return false; } else if (exp[i] == '}') { if (top == -1 || stack[top--] != '{') return false; } } return top == -1; } |
| 5 | Infix to postfix conversion | Convert arithmetic expressions from infix to postfix notation using operator precedence. |
int precedence(char op) {
if (op == '^') return 3; if (op == '*' || op == '/') return 2; if (op == '+' || op == '-') return 1; return 0; } // Main conversion logic snippet while (!isEmpty(stack) && precedence(peek(stack)) >= precedence(token)) { postfix[j++] = pop(stack); } push(stack, token); |
| 6 | Postfix evaluation | Evaluate postfix expressions by pushing operands and applying operators. |
int evaluatePostfix(char* exp) {
int stack[MAX], top = -1; for (int i = 0; exp[i]; i++) { if (isdigit(exp[i])) { stack[++top] = exp[i] - '0'; } else { int val1 = stack[top--]; int val2 = stack[top--]; switch (exp[i]) { case '+': stack[++top] = val2 + val1; break; case '-': stack[++top] = val2 - val1; break; case '*': stack[++top] = val2 * val1; break; case '/': stack[++top] = val2 / val1; break; } } } return stack[top]; } |
| 7 | Stock span problem | Calculate span of stock prices where span is days of consecutive lower prices. |
void calculateSpan(int price[], int n, int S[]) {
int stack[n], top = -1; stack[++top] = 0; S[0] = 1; for (int i = 1; i < n; i++) { while (top != -1 && price[stack[top]] <= price[i]) { top--; } S[i] = (top == -1) ? (i + 1) : (i - stack[top]); stack[++top] = i; } } |
| 8 | Next greater element | For each element, find next greater element to its right in the array. |
void nextGreater(int arr[], int n) {
int stack[n], top = -1; int res[n]; for (int i = n-1; i >= 0; i--) { while (top != -1 && stack[top] <= arr[i]) { top--; } res[i] = (top == -1) ? -1 : stack[top]; stack[++top] = arr[i]; } // Print res[] for next greater elements } |
| 9 | Minimum stack | Stack that supports push, pop and getMin in O(1) time using auxiliary stack. |
typedef struct {
int mainStack[MAX], minStack[MAX]; int top; } MinStack; void push(MinStack* obj, int x) { obj->mainStack[++obj->top] = x; if (obj->top == 0 || x <= obj->minStack[obj->top-1]) { obj->minStack[obj->top] = x; } else { obj->minStack[obj->top] = obj->minStack[obj->top-1]; } } int getMin(MinStack* obj) { return obj->minStack[obj->top]; } |
| 10 | Reverse stack using recursion | Reverse stack elements without using additional data structures. |
void insertAtBottom(int stack[], int* top, int item) {
if (*top == -1) { stack[++(*top)] = item; } else { int temp = stack[(*top)--]; insertAtBottom(stack, top, item); stack[++(*top)] = temp; } } void reverseStack(int stack[], int* top) { if (*top != -1) { int temp = stack[(*top)--]; reverseStack(stack, top); insertAtBottom(stack, top, temp); } } |
| 11 | Histogram area calculation | Calculate largest rectangle in histogram using stack. |
int largestRectangleArea(int* heights, int n) {
int stack[n], top = -1; int max_area = 0; int i = 0; while (i < n) { if (top == -1 || heights[stack[top]] <= heights[i]) { stack[++top] = i++; } else { int tp = stack[top--]; int area = heights[tp] * (top == -1 ? i : i - stack[top] - 1); if (area > max_area) max_area = area; } } return max_area; } |
| 12 | DFS with explicit stack | Implement depth-first search using stack instead of recursion. |
void DFS(int start, int n, int adj[][n]) {
int visited[n] = {0}; int stack[n], top = -1; stack[++top] = start; visited[start] = 1; while (top != -1) { int v = stack[top--]; printf("%d ", v); for (int i = 0; i < n; i++) { if (adj[v][i] && !visited[i]) { stack[++top] = i; visited[i] = 1; } } } } |
| 13 | Iterative tower of Hanoi | Solve tower of Hanoi problem using stack simulation. |
typedef struct {
int n, from, to, aux; } HanoiFrame; void iterativeHanoi(int n) { HanoiFrame stack[2*n], temp; int top = -1; stack[++top] = (HanoiFrame){n, 1, 3, 2}; while (top >= 0) { HanoiFrame current = stack[top--]; if (current.n == 1) { printf("Move disk 1 from %d to %d\n", current.from, current.to); } else { stack[++top] = (HanoiFrame){current.n-1, current.aux, current.to, current.from}; stack[++top] = (HanoiFrame){1, current.from, current.to, current.aux}; stack[++top] = (HanoiFrame){current.n-1, current.from, current.aux, current.to}; } } } |
| 14 | Undo/Redo operations | Implement undo-redo functionality using two stacks. |
typedef struct {
char* action; } Command; Command undoStack[MAX], redoStack[MAX]; int undoTop = -1, redoTop = -1; void execute(Command cmd) { // Execute command undoStack[++undoTop] = cmd; redoTop = -1; // Clear redo stack } void undo() { if (undoTop >= 0) { Command cmd = undoStack[undoTop--]; // Reverse cmd action redoStack[++redoTop] = cmd; } } |
| 15 | Browser history simulation | Simulate back/forward navigation using two stacks. |
char* backStack[MAX], *forwardStack[MAX];
int backTop = -1, forwardTop = -1; char* currentPage = NULL; void visitPage(char* url) { if (currentPage) { backStack[++backTop] = currentPage; } currentPage = url; forwardTop = -1; // Clear forward stack } void goBack() { if (backTop >= 0) { forwardStack[++forwardTop] = currentPage; currentPage = backStack[backTop--]; } } |