#include <stdio.h>
#include
<stdlib.h>
#include
<ctype.h>
#define MAX_STACK_SIZE 100
{ int top;
int items[MAX_STACK_SIZE];
};
{ stack->top = -1;
}
void push(struct Stack* stack, int value)
{
if (stack->top >= MAX_STACK_SIZE - 1)
{
printf("Stack Overflow\n");
exit(1);
}
stack->items[++stack->top] = value;
}
int
pop(struct Stack* stack)
{
if (stack->top == -1)
{
printf("Stack Underflow\n");
exit(1);
}
return stack->items[stack->top--];
}
int
evaluatePostfix(char expression[], int values[])
{
struct Stack stack;
initializeStack(&stack);
for (int i = 0; expression[i]; i++)
{
if (isdigit(expression[i]))
{
push(&stack, values[expression[i]
- 'a']);
}
else
{
int operand2 = pop(&stack);
int operand1 = pop(&stack);
switch (expression[i])
{
case '+': push(&stack,
operand1 + operand2); break;
case '-': push(&stack,
operand1 - operand2); break;
case '*': push(&stack,
operand1 * operand2); break;
case '/': push(&stack,
operand1 / operand2); break;
}
}
}
return pop(&stack);
}
void
main()
{ char postfix[100];
int values[26];
printf("Enter postfix expression:
");
scanf("%s", postfix);
for (int i = 0; i < 26; i++) {
printf("Enter value for %c:
", 'a' + i);
scanf("%d", &values[i]);
}
printf("Answer: %d\n",
evaluatePostfix(postfix, values));
}
No comments:
Post a Comment