Certainly! Here's an example code in C language to convert an infix expression to its equivalent postfix expression using single character variables:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// Stack implementation
typedef struct {
char stack[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isStackEmpty(Stack *s) {
return (s->top == -1);
}
void push(Stack *s, char item) {
if (s->top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
} else {
s->stack[++s->top] = item;
}
}
char pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack Underflow\n");
return '\0';
} else {
return s->stack[s->top--];
}
}
char peek(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty\n");
return '\0';
} else {
return s->stack[s->top];
}
}
// Function to check if the given character is an operator
int isOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return 1;
}
return 0;
}
// Function to get the precedence of the operator
int getPrecedence(char c) {
if (c == '*' || c == '/') {
return 2;
} else if (c == '+' || c == '-') {
return 1;
} else {
return -1;
}
}
// Function to convert infix expression to postfix expression
void infixToPostfix(char *infix, char *postfix) {
Stack s;
int i, j;
initStack(&s);
j = 0;
for (i = 0; i < strlen(infix); i++) {
char c = infix[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
postfix[j++] = c;
} else if (isOperator(c)) {
while (!isStackEmpty(&s) && getPrecedence(peek(&s)) >= getPrecedence(c)) {
postfix[j++] = pop(&s);
}
push(&s, c);
} else if (c == '(') {
push(&s, c);
} else if (c == ')') {
while (!isStackEmpty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
}
pop(&s); // Pop the '(' from stack
}
}
while (!isStackEmpty(&s)) {
postfix[j++] = pop(&s);
}
postfix[j] = '\0';
}
int main() {
char infix[MAX_SIZE];
char postfix[MAX_SIZE];
printf("Enter the infix expression: ");
fgets(infix, MAX_SIZE, stdin);
infix[strlen(infix) - 1] = '\0';
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}
To test the program, you can run it and provide an input infix expression when prompted. The program will then convert the infix expression to postfix and display the output.