C++ 用波兰语表示法计算
我有以下代码:C++ 用波兰语表示法计算,c++,stack,notation,C++,Stack,Notation,我有以下代码: #include <iostream> #include <string> #include “stack.h” int main (int argc, char *argv[]) { char *a = argv[1]; int N = strlen(a); stack<int> polish(N); int el; for (int i = 0; i < N; i++){ if (a[i] ==
#include <iostream>
#include <string>
#include “stack.h”
int main (int argc, char *argv[]) {
char *a = argv[1];
int N = strlen(a);
stack<int> polish(N); int el;
for (int i = 0; i < N; i++){
if (a[i] == '+'){
el = polish.readStack(); polish.outofStack();
polish.inStack( el + polish.readStack()); polish.outofStack()
}
if (a[i] == '*'){
el = polish.readStack(); polish.outofStack();
polish.inStack(el * polish.readStack()); polish.outofStack()
}
if ((a[i] >= '0') && (a[i] <= '9')){
el = polish.readStack(); polish.outofStack()
polish.inStack(10 * el + (a[i++]-'0'));
}
}
cout << polish.outofStack() << endl;
}
它看起来像是一个读取和计算的算法 比如说,
1 2 3 + 4 - -
意味着
i、 e
此代码行:
polish.inStack(10 * el + (a[i++]-'0'));
应该通过追加数字来组合数字。(a[i++]-'0')
正在从字符数字如'3'转换为整数3
最初,我们的堆栈中有一个零。
例如,如果您有“123”,它将按如下方式逐字符读取它们:
1
。从堆栈(0)中获取最后一个数字,使0*10+1
=1。把它推回堆栈2
。从堆栈(1)中获取最后一个数字,使1*10+2
=12。推回3
。从堆栈(12)中获取最后一个数字,使12*10+3
=123。把它推回去Pop
和Push
,而不是readStack()
和inStack()
readStack()
不提供该选项if
s而不是switch
语句这样一个奇怪的
堆栈实现
。众所周知,调用方法push
和pop
,而不是readStack
和inStack
。另外,pop
应该自动删除最后一个元素,而不调用outOfStack
。如果我错了,请纠正我,但这不应该起作用:操作的结果我们被推入堆栈(不删除第二个操作数),然后被丢弃<代码>polish.inStack(10*el+(a[i++]-'0')如果假设stack::readStack()
返回一个int
,这意味着您将传递10*该调用的结果+作为stack::inStack()输入的下一个字符
@YeldarKurmangaliyev看起来像是一个非标准名称的标准界面--inStack
是push
,readStack
是top
,outOfStack
是pop
。通常还有peek
,它正在做readStack
似乎正在做的事情。
Add 1; add 2; add 3; sum up the last two; add 4; substract the last two; substract the last two.
1 - ((2 + 3) - 4) = 0
polish.inStack(10 * el + (a[i++]-'0'));