Skip to content

Instantly share code, notes, and snippets.

@lakshyaraj2006
Last active September 1, 2025 05:22
Show Gist options
  • Select an option

  • Save lakshyaraj2006/1bd62d57c10ff811053993383a407c6a to your computer and use it in GitHub Desktop.

Select an option

Save lakshyaraj2006/1bd62d57c10ff811053993383a407c6a to your computer and use it in GitHub Desktop.
A C program to convert infix notation to postfix notation.
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
struct Stack {
int size;
int top;
char *arr;
};
int isFull(struct Stack * sp) {
if (sp->top == sp->size-1) {
return 1;
}
return 0;
}
int isEmpty(struct Stack * sp) {
if (sp->top == -1) {
return 1;
}
return 0;
}
int precedence(char c) {
if (c == '^') {
return 3;
} else if (c == '*' || c == '/' || c == '%') {
return 2;
} else if (c == '+' || c == '-') {
return 1;
} else if (c == '&') {
return 0;
} else if (c == '|') {
return -1;
}
return -2;
}
bool isOperator(char c) {
if (
c == '^' || c == '&' || c == '|' || c == '/' || c == '*' || c == '+' || c == '-'
) {
return true;
} else {
return false;
}
}
char pop(struct Stack * sp) {
if (isEmpty(sp)) {
printf("Stack Undeflow! Cannot pop from the stack\n");
return -1;
}
else {
int val = sp->arr[sp->top];
sp->top--;
return val;
}
}
void push(struct Stack * sp, char val) {
if (isFull(sp)) {
printf("Stack Overflow! Cannot push %d to the stack\n", val);
}
else {
sp->top++;
sp->arr[sp->top] = val;
}
}
char stackTop(struct Stack * sp) {
return sp->arr[sp->top];
}
int main(){
struct Stack * sp = (struct Stack *)malloc(sizeof(struct Stack));
char * exp = "M^(N*P)/Q+R-S^T/((U/V)/W)-X";
sp->size = strlen(exp);
sp->top = -1;
sp->arr = (char *)malloc(sp->size * sizeof(char));
char * postfix = (char *)malloc((sp->size + 1) * sizeof(char));
int k = 0;
for (int i = 0; exp[i] != '\0'; i++)
{
if (isalnum(exp[i])) {
postfix[k++] = exp[i];
} else if (exp[i] == '(') {
push(sp, exp[i]);
}
else if (exp[i] == ')') {
while (!isEmpty(sp) && stackTop(sp) != '(') {
postfix[k++] = pop(sp);
}
pop(sp);
} else if (isOperator(exp[i])) {
while (!isEmpty(sp) && precedence(stackTop(sp)) >= precedence(exp[i]))
{
postfix[k++] = pop(sp);
}
push(sp, exp[i]);
}
}
while (!isEmpty(sp)) {
postfix[k++] = pop(sp);
}
postfix[k] = '\0';
printf("%s", postfix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment