我用堆栈找不到前缀号的和

I can not find sum of the prefix number using stack

本文关键字:前缀 找不到 堆栈      更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
class StackNode
{
public:
StackNode *  topPtr = NULL;
StackNode* next;
string item;
bool push( string newItem) {
// create a new node
StackNode *newPtr = new StackNode;
// set data portion  of new node
newPtr->item = newItem;
// insert the new node
newPtr->next = topPtr;
topPtr = newPtr;
return true;
}
bool pop() {
if (topPtr == NULL)
return false;
// stack is not empty; delete top
else{
StackNode *temp = topPtr;
topPtr = topPtr->next;
// return deleted node to system
temp->next = NULL;  // safeguard
delete temp;
return true;
}
}
int ope(string op, string val1,string val2)
{
int vaL1 = stoi(val1);
int vaL2 = stoi(val2);
int res = 0;
if( op == "*")
res = vaL1 * vaL2;
if( op == "/")
res = vaL1 / vaL2;
if( op == "-")
res = vaL1 - vaL2;
if( op == "+")
res = vaL1 + vaL2;
return res;
}
int cal(string pre_exp[],int len)
{
int numb = 0;
for(int i = len -1;i>=0;i--)
{
if ( pre_exp[i] == "*" || pre_exp[i] == "/" || pre_exp[i] == "+" || pre_exp[i] == "-")
{
string op1 = topPtr->item;
pop();
string op2 = topPtr->item;
pop();
numb = numb + ope(pre_exp[i],op1,op2);
}
else
{
push( (pre_exp[i]));
}
}
return numb;
}
int main()
{
StackNode nbr;
string eyoo[] = {"+","-","2","3","9"};
cout<< nbr.cal(eyoo,5)<<endl;
return 0;
}

大家好,我正在努力寻找一个前缀表达式的和。我的代码在这里。奇怪的是,我没有得到任何输出。方法cal不返回数字,可能程序在方法calc的for循环中卡住了。有人能帮我吗?弹出和推送方法都有效,我用显示方法测试了它们。正如我所说,问题一定是在stoi的使用或calc方法中。

string op1 = topPtr->item;
pop();
string op2 = topPtr->item;
pop();

您总是弹出一个运算符的2个操作数,假设您推送结果,但您没有这样做,在给定的时间topPtr变为null,您的示例是当您执行string op2 = topPtr->item;

对我来说,必须通过在堆栈中两个弹出值的位置推送ope(pre_exp[i],op1,op2)的结果来替换numb = numb + ope(pre_exp[i],op1,op2);

所以对于{"+","-","2","3","9"}:

  • 推9
  • 推动3
  • 推2
  • -所以pop=2-pop=3=-1,你必须按下-1
  • +所以pop=-1+pop=9=8,然后按8(在获取第二个操作数时堆栈为空之前不按-1)
  • 一切都完成了,所以你弹出结果=8

然而,我很惊讶你在表达式的末尾,我不确定在所有情况下都能很好地计算结果,为什么你不从头开始?


最后一句话:你所有的方法都试图内联(在类中定义),当一个方法很小时,我们使用内联,最好将你的方法的定义移出类