Top 4 Stack Problems (with Input) - Simple Format
1. Min Stack (with user input)
#include <stdio.h>
#include <limits.h>
#define MAX 1000
int stack[MAX], minStack[MAX];
int top1 = -1, top2 = -1;
void push(int val) {
stack[++top1] = val;
if (top2 == -1 || val <= minStack[top2]) {
minStack[++top2] = val;
}
}
void pop() {
if (top1 == -1) {
printf("Stack is empty\n");
return;
}
if (stack[top1] == minStack[top2]) top2--;
top1--;
}
int top() {
if (top1 == -1) return -1;
return stack[top1];
}
int getMin() {
if (top2 == -1) return -1;
return minStack[top2];
}
int main() {
int choice, val;
while (1) {
printf("\n1.Push 2.Pop 3.Top 4.GetMin 5.Exit\nEnter choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("Enter value: ");
scanf("%d", &val);
push(val);
} else if (choice == 2) {
pop();
} else if (choice == 3) {
printf("Top element: %d\n", top());
} else if (choice == 4) {
printf("Minimum: %d\n", getMin());
} else {
break;
}
}
return 0;
}
2. Valid Parentheses (with string input)
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isValid(char *s) {
char stack[1000];
int top = -1;
for (int i = 0; s[i]; i++) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
stack[++top] = s[i];
else {
if (top == -1) return false;
char open = stack[top--];
if ((s[i] == ')' && open != '(') ||
(s[i] == '}' && open != '{') ||
(s[i] == ']' && open != '['))
return false;
}
}
return top == -1;
}
int main() {
char str[1000];
printf("Enter parentheses: ");
scanf("%s", str);
if (isValid(str))
printf("Valid\n");
else
printf("Invalid\n");
return 0;
}
3. Daily Temperatures (simple version)
#include <stdio.h>
int main() {
int n;
printf("Enter number of days: ");
scanf("%d", &n);
int temp[n], answer[n], stack[n], top = -1;
printf("Enter temperatures: ");
for (int i = 0; i < n; i++) scanf("%d", &temp[i]);
for (int i = 0; i < n; i++) {
while (top != -1 && temp[i] > temp[stack[top]]) {
int idx = stack[top--];
answer[idx] = i - idx;
}
stack[++top] = i;
}
for (int i = 0; i < n; i++)
if (answer[i] == 0)
answer[i] = 0;
printf("Result: ");
for (int i = 0; i < n; i++)
printf("%d ", answer[i]);
return 0;
}
4. Reverse Polish Notation (with input)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int evalRPN(char** tokens, int size) {
int stack[1000], top = -1;
for (int i = 0; i < size; i++) {
char *t = tokens[i];
if (strcmp(t, "+") == 0 || strcmp(t, "-") == 0 ||
strcmp(t, "*") == 0 || strcmp(t, "/") == 0) {
int b = stack[top--];
int a = stack[top--];
if (strcmp(t, "+") == 0) stack[++top] = a + b;
else if (strcmp(t, "-") == 0) stack[++top] = a - b;
else if (strcmp(t, "*") == 0) stack[++top] = a * b;
else stack[++top] = a / b;
} else {
stack[++top] = atoi(t);
}
}
return stack[top];
}
int main() {
char *tokens[] = {"2", "1", "+", "3", "*"};
int size = 5;
printf("Result: %d\n", evalRPN(tokens, size));
return 0;
}