Untitled
unknown
plain_text
2 years ago
3.5 kB
7
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_SIZE 100
struct Stack {
int top;
char arr[MAX_SIZE];
};
void initialize(struct Stack *stack) {
stack->top = -1;
}
bool isEmpty(struct Stack *stack) {
return (stack->top == -1);
}
bool isFull(struct Stack *stack) {
return (stack->top == MAX_SIZE - 1);
}
void push(struct Stack *stack, char ch) {
if (isFull(stack)) {
printf("Stack Overflow\n");
exit(EXIT_FAILURE);
}
stack->arr[++stack->top] = ch;
}
char pop(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}
return stack->arr[stack->top--];
}
char peek(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is Empty\n");
exit(EXIT_FAILURE);
}
return stack->arr[stack->top];
}
bool isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
int precedence(char ch) {
if (ch == '+' || ch == '-')
return 1;
else if (ch == '*' || ch == '/')
return 2;
return 0;
}
void infixToPostfix(char infix[], char postfix[]) {
struct Stack stack;
initialize(&stack);
int i = 0, j = 0;
while (infix[i] != '\0') {
char ch = infix[i];
if (isalnum(ch)) {
postfix[j++] = ch;
} else if (ch == '(') {
push(&stack, ch);
} else if (ch == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[j++] = pop(&stack);
}
pop(&stack);
} else if (isOperator(ch)) {
while (!isEmpty(&stack) && precedence(ch) <= precedence(peek(&stack))) {
postfix[j++] = pop(&stack);
}
push(&stack, ch);
}
i++;
}
while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\0';
}
void infixToPrefix(char infix[], char prefix[]) {
struct Stack stack;
initialize(&stack);
char temp[MAX_SIZE];
int i, j;
strcpy(temp, infix);
// Reverse the infix expression
strrev(temp);
for (i = 0; temp[i] != '\0'; i++) {
if (temp[i] == '(')
temp[i] = ')';
else if (temp[i] == ')')
temp[i] = '(';
}
// Convert the reversed infix expression to postfix
char postfix[MAX_SIZE];
infixToPostfix(temp, postfix);
// Reverse the postfix expression to get the prefix expression
strrev(postfix);
strcpy(prefix, postfix);
}
int main() {
char infix[MAX_SIZE], prefix[MAX_SIZE], postfix[MAX_SIZE];
int choice;
printf("Enter the infix expression: ");
gets(infix);
do {
printf("\nMenu\n");
printf("1. Convert to prefix expression\n");
printf("2. Convert to postfix expression\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
infixToPrefix(infix, prefix);
printf("Prefix Expression: %s\n", prefix);
break;
case 2:
infixToPostfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 3);
return 0;
}
Editor is loading...