Infix to Postfix Conversion
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
struct Stack {
char items[MAX_SIZE];
int top;
};
void initialize(struct Stack *stack);
void push(struct Stack *stack, char item);
char pop(struct Stack *stack);
char peek(struct Stack *stack);
int isOperator(char ch);
int precedence(char ch);
void infixToPostfix(char infix[], char postfix[]);
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Enter a valid parenthesized infix expression: ");
fgets(infix, MAX_SIZE, stdin);
infix[strlen(infix) - 1] = '\\0';
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\\n", postfix);
return 0;
}
void initialize(struct Stack *stack) {
stack->top = -1;
}
void push(struct Stack *stack, char item) {
stack->items[++stack->top] = item;
}
char pop(struct Stack *stack) {
return stack->items[stack->top--];
}
char peek(struct Stack *stack) {
return stack->items[stack->top];
}
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
void infixToPostfix(char infix[], char postfix[]) {
struct Stack stack;
initialize(&stack);
int i, j;
char token, popped;
j = 0;
for (i = 0; infix[i] != '\\0'; ++i) {
token = infix[i];
if (isalnum(token)) {
postfix[j++] = token;
} else if (token == '(') {
push(&stack, token);
} else if (token == ')') {
while (peek(&stack) != '(') {
postfix[j++] = pop(&stack);
}
popped = pop(&stack);
} else if (isOperator(token)) {
while (!isEmpty(&stack) && precedence(token) <= precedence(peek(&stack))) {
postfix[j++] = pop(&stack);
}
push(&stack, token);
}
}
while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\\0';
}
int isEmpty(struct Stack *stack) {
return stack->top == -1;
}