【问题标题】:C++ evaluating an arithmetic expression in RPN format using ADT stack [closed]C ++使用ADT堆栈评估RPN格式的算术表达式[关闭]
【发布时间】:2021-08-18 05:21:12
【问题描述】:

编写一个程序,使用 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;
}

问题:

我不确定这是否正确,也不知道是否有办法缩短代码或使其更好。

【问题讨论】:

标签: c++ algorithm sorting stack adt


【解决方案1】:

我发现了一些问题:

  • 如果堆栈没有成功创建你return -1; 来自postfixEvaluation(),但你没有在主函数中处理它,它可能会导致一些错误消息和主函数中的return -1;
  • 您正在将数字一个一个地推入堆栈 - 因此输入的 74 变为 7 和 4 作为堆栈上的单独数字,不是吗?
  • 您可以设置默认值 在 postfixEvaluation 内的 switch 内添加标签以处理非法 输入中的运算符
  • 您正在分配堆栈和堆栈内的数组,但您没有释放内存(您可以使用valgrind 检查内存泄漏)

如果您需要一些参考来检查,其中还包括括号和函数:https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2023-03-19
    • 2020-07-15
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多