问题描述
编写一个程序,使用 ADT 堆栈来计算 rpn 格式的算术表达式。在评估期间,堆栈的内容应显示在屏幕上。允许的算术运算符是 +、-、x 和 /。
到目前为止我做了什么:
#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;
}
问题:
我不确定这是否正确,也不知道是否有办法缩短代码或使其更好。
解决方法
我发现了一些问题:
- 如果堆栈没有成功创建,您从
return -1;
postfixEvaluation()
,但您没有在 main 函数中处理它,它可能会导致一些错误消息和return -1;
在 main - 您正在将数字一个一个地压入堆栈 - 以便输入的 74 变为 7 和 4 作为堆栈上的单独数字,不是吗?
- 你可以设置一个默认值 标签内开关内 postfixEvaluation 处理非法 输入操作符
- 您正在对堆栈和堆栈内部的数组进行 malloc,但您并未释放内存(您可以使用 valgrind 来检查内存泄漏)
如果您需要一些参考来检查,其中还包括括号和函数:https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail