我用堆栈找不到前缀号的和
I can not find sum of the prefix number using stack
#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
然而,我很惊讶你在表达式的末尾,我不确定在所有情况下都能很好地计算结果,为什么你不从头开始?
最后一句话:你所有的方法都试图内联(在类中定义),当一个方法很小时,我们使用内联,最好将你的方法的定义移出类
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 找不到QtResource文件中的文件
- VC++本机单元测试,找不到调试符号
- RegGetValue在当前用户下找不到名称
- 带有 -stdlib=libc++ 的 clang++ 9.0.1 找不到<optional>
- c++找不到具有相同哈希的无序集合元素
- 找不到以下加速库:boost_fiber
- 找不到 FLTK(缺少:FLTK_INCLUDE_DIR)
- 设置 Visual Studio for MPI: 找不到标识符错误
- "assimp/config.h"找不到,但它在文件夹中
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- C++系统找不到指定的文件错误
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- vcpkg 添加新库,但找不到
- Qt 5.11.2 (Clang 8.0 (Apple), 64 位), 找不到 QJSEngine 文件
- 我用堆栈找不到前缀号的和