Write a program that uses an ADT Stack to evaluate arithmetic expressions in RPN format. The contents of the stack should be displayed on the screen during evaluation. The allowed arithmetic operators are +, -, x, and /.
What I have done so far:
#include <iostream>
#include <string.h>
using namespace std;
struct Stack
{
int top;
unsigned cap;
int* arr;
};
struct Stack* createStackFun(unsigned capacity)
{
struct Stack* s = (struct Stack*) malloc(sizeof(struct Stack));
if (!s) return NULL;
s->top = -1;
s->cap = capacity;
s->arr = (int*)malloc(s->cap * sizeof(int));
if (!s->arr) return NULL;
return s;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
char peek(struct Stack* stack)
{
return stack->arr[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->arr[stack->top--];
return '$';
}
void push(struct Stack* stack, char op)
{
stack->arr[++stack->top] = op;
}
int postfixEvaluation(char* exp)
{
// Create a stack of capacity equal to expression size
struct Stack* stack = createStackFun(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 (number here), 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);
}
int main()
{
char expression[] = "74*+8-";
cout << "Postfix Evaluation: " << postfixEvaluation(expression);
return 0;
}
The problem:
I am not sure if this is correct and I don't know if there is a way to shorten the code or make it better.