Skip to content

Instantly share code, notes, and snippets.

@kek-Sec
Created September 12, 2024 08:46
Show Gist options
  • Save kek-Sec/d2237ab5d9b302ee85508bb3613f7e97 to your computer and use it in GitHub Desktop.
Save kek-Sec/d2237ab5d9b302ee85508bb3613f7e97 to your computer and use it in GitHub Desktop.
postfix <=> infix
#include <stdio.h>
#include <ctype.h> // For isdigit() and isalpha()
#include <string.h> // For strlen()
#define MAX 100 // Maximum size of the stack
char stack[MAX];
int top = -1;
// Function to push onto the stack
void push(char item) {
if (top >= MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = item;
}
}
// Function to pop from the stack
char pop() {
if (top < 0) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
// Function to return precedence of operators
int precedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
} else if (operator == '^') {
return 3;
}
return 0;
}
// Function to check if the character is an operator
int isOperator(char symbol) {
return (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' || symbol == '^');
}
// Infix to Postfix conversion function
void infixToPostfix(char infix[], char postfix[]) {
int i, j = 0;
char symbol, temp;
for (i = 0; i < strlen(infix); i++) {
symbol = infix[i];
// If the character is an operand (letter or digit), add to the postfix expression
if (isalnum(symbol)) {
postfix[j++] = symbol;
}
// If the character is an opening parenthesis, push it onto the stack
else if (symbol == '(') {
push(symbol);
}
// If the character is a closing parenthesis, pop from the stack until '(' is found
else if (symbol == ')') {
while ((temp = pop()) != '(') {
postfix[j++] = temp;
}
}
// If the character is an operator
else if (isOperator(symbol)) {
while (top != -1 && precedence(stack[top]) >= precedence(symbol)) {
postfix[j++] = pop();
}
push(symbol);
}
}
// Pop all remaining operators from the stack
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0'; // Null terminate the postfix expression
}
int main() {
char infix[MAX], postfix[MAX];
printf("Enter an infix expression: ");
gets(infix); // Using gets() for simplicity, but it's unsafe in production code
infixToPostfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment