我有这段代码:
#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;
}
它是如何工作的?这条线是什么意思?
polish.inStack(10 * el + (a[i++]-'0'));
答案 0 :(得分:0)
看起来它是一种读取和计算Reverse (postfix) Polish notation的算法。
例如,
1 2 3 + 4 - -
装置
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'));
应该通过附加数字来组合数字
(a[i++]-'0')
正在转换为char数字,例如&#39; 3&#39;到整数3。
最初,我们的堆栈中有零。 例如,如果你有&#34; 123&#34;,它将通过char以这种方式读取它们:
阅读1
。从堆栈中获取最后一个数字(0),使0 * 10 + 1
= 1.将其推回堆栈
阅读2
。从堆栈中获取最后一个数字(1),使1 * 10 + 2
= 12.将其推回
阅读3
。从堆栈中获取最后一个数字(12),使12 * 10 + 3
= 123.将其推回。
大!已读取123号码。
但是,此代码示例是一堆不良做法。
Pop
和Push
,但不是readStack()
和inStack()
。readStack()
未提供此内容。if
而不是switch
声明。