【发布时间】:2011-12-05 16:47:57
【问题描述】:
我正在尝试理解这段代码。它做什么它后缀表达式评估。我在理解代码时遇到问题。如果有人可以帮助我,我将非常感激。
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int main()
{
//suppose a contains the string..
//n is the length of string...
char a[10]="A+B/C";
int n = strlen(a)
stack<int>s;
for (int i=0;i<n;i++)
{
if (a[i]=='+')
{
s.push(s.pop()+s.pop());
int temp1 = s.top();
s.pop();
int temp2 = s.top();
s.pop();
s.push(temp1 * temp2);
}
if (a[i]=='*')
s.push(s.pop() * s.pop());
if ((a[i]>='0') && (a[i]<='9'))
s.push(0);
while ((a[i]>='0') && (a[i]<='9'))
s.push(10*s.pop()+(a[i++]-'0'));
}
cout<<s.pop()<<endl;
return 0;
}
提前致谢。
【问题讨论】:
-
你为
a写过那个例子吗?因为它不是后缀。 -
stack::pop() 是一个空函数。
这段代码一团糟。只需在 SO 上搜索后缀计算器,您就会找到几十个(更好的)sn-ps -
为了好玩和咯咯笑,这是我很久以前写的:stackoverflow.com/questions/5631345/…
-
我修复了缩进(看起来像是混合空格和制表符被错误扩展的结果),但仍然缺少分号,当然
pop()的使用不正确。