int precedence(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 0; } } // Function to convert infix expression to postfix void infixToPostfix(char* infix, char* postfix) { struct Stack stack; initialize(&stack); int i, j = 0;
for (i = 0; i < strlen(infix); i++) {
char ch = infix[i];
// If the character is an operand, add it to the output
if (isalnum(ch)) { postfix[j++] = ch; } // If the character is '(', push it onto the stack else if (ch == '(') { push(&stack, ch); } // If the character is ')', pop and output from the stack until '(' is found else if (ch == ')') { while (!isEmpty(&stack) && peek(&stack) != '(') { postfix[j++] = pop(&stack); } pop(&stack); // Pop '(' from the stack } // If the character is an operator else if (isOperator(ch)) { while (!isEmpty(&stack) && precedence(peek(&stack)) >= precedence(ch)) { postfix[j++] = pop(&stack); } push(&stack, ch); } }
// Pop all the remaining operators from the stack
while (!isEmpty(&stack)) { postfix[j++] = pop(&stack); } postfix[j] = '\0'; // Null-terminate the postfix expression } // Main function int main() { char infix[SIZE], postfix[SIZE];