Skip to content

Instantly share code, notes, and snippets.

@raiyansarker
Created March 2, 2026 22:50
Show Gist options
  • Select an option

  • Save raiyansarker/455eb8428ac38951c48f2375c0dd5b5c to your computer and use it in GitHub Desktop.

Select an option

Save raiyansarker/455eb8428ac38951c48f2375c0dd5b5c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define MAX_SIZE 100
typedef struct Stack {
int arr[MAX_SIZE];
int top;
} Stack;
Stack* init() {
Stack *s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
return s;
}
void push(Stack *s, int data) {
s->arr[++(s->top)] = data;
}
int pop(Stack *s) {
return s->top == -1 ? -1 : s->arr[s->top--];
}
int peak(Stack *s) {
return s->top == -1 ? -1 : s->arr[s->top];
}
int main() {
char buff[50];
scanf("%s", buff);
Stack *s = init();
for (size_t i = 0; buff[i] != '\0'; i++) {
if (isdigit(buff[i])) {
push(s, buff[i] - '0');
} else {
int o2 = pop(s), o1 = pop(s);
switch(buff[i]) {
case '+': push(s, o1 + o2); break;
case '-': push(s, o1 - o2); break;
case '*': push(s, o1 * o2); break;
case '/': push(s, o1 / o2); break;
case '^': push(s, pow(o1, o2)); break;
default: return 1;
}
}
}
printf("Result = %d\n", peak(s));
}
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Stack {
char arr[MAX_SIZE];
int top;
} Stack;
Stack* init() {
Stack *s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
return s;
}
void push(Stack *s, int data) {
s->arr[++(s->top)] = data;
}
int pop(Stack *s) {
return s->top == -1 ? -1 : s->arr[s->top--];
}
int peak(Stack *s) {
return s->top == -1 ? -1 : s->arr[s->top];
}
int priority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
int is_operand(char c) {
if (
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9')
) {
return 1;
}
return 0;
}
int main() {
char buff[50];
scanf("%49[^\n]s", buff);
char ans[50];
size_t j = 0;
Stack *s = init();
for (size_t i = 0; buff[i] != '\0'; i++) {
if (is_operand(buff[i])) {
ans[j++] = buff[i];
} else if (buff[i] == ')') {
while (s->top != -1 && peak(s) != '(') {
ans[j++] = peak(s);
pop(s);
}
pop(s);
} else if (buff[i] == '(') {
push(s, '(');
} else {
while (s->top != -1 && peak(s) != '(' && priority(peak(s)) >= priority(buff[i])) {
ans[j++] = peak(s);
pop(s);
}
push(s, buff[i]);
}
}
while (s->top != -1) {
ans[j++] = peak(s);
pop(s);
}
ans[j] = '\0';
printf("%s\n", ans);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment