design and implement a class of postfix calculators use the
design and implement a class of postfix calculators. use the algorithm given in this chapter to evaluate postfix expressions , as entered into the calculator . use only the operators +, - ,*, %, and /. assume that the postfix expressions have single digit numbers in the expression and are syntactically correct. Read the input as a string from console. First, you convert the infix expression into postfix expression. When you store each operand or operator into the post-fix expression, you place a space right after it. If it is not a correct infix expression, report the error, otherwise, perform the postfix evaluation. When evaluating the postfix expression, you can use the class StringTokenizer since there are spaces as delimiters. Pick off the characters one at a time using charAt. If they are operands, push them; if operator, pop two operands and apply, pushing the result. When the end of the string is, report the top of the stack as the result in c++ language
Solution
hidbddhh
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
// Stack type
struct Stack
{
int top;
unsigned capacity;
int* array;
};
// Stack Operations
struct Stack* createStack( unsigned capacity )
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
if (!stack) return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
if (!stack->array) return NULL;
return stack;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1 ;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return \'$\';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}
// The main function that returns value of a given postfix expression
int evaluatePostfix(char* exp)
{
// Create a stack of capacity equal to expression size
struct Stack* stack = createStack(strlen(exp));
int i;
// See if stack was created successfully
if (!stack) return -1;
// Scan all characters one by one
for (i = 0; exp[i]; ++i)
{
// If the scanned character is an operand or number,
// push it to the stack.
if (isdigit(exp[i]))
push(stack, exp[i] - \'0\');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case \'+\': push(stack, val2 + val1); break;
case \'-\': push(stack, val2 - val1); break;
case \'*\': push(stack, val2 * val1); break;
case \'/\': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}
// Driver program to test above functions
int main()
{
char exp[] = \" / * + -\";
printf (\"Value of %s is %d\", exp, evaluatePostfix(exp));
return 0
}



