用波兰表示法计算

时间:2015-07-03 08:27:03

标签: 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] == '+'){
         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'));

1 个答案:

答案 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. 阅读1。从堆栈中获取最后一个数字(0),使0 * 10 + 1 = 1.将其推回堆栈

  2. 阅读2。从堆栈中获取最后一个数字(1),使1 * 10 + 2 = 12.将其推回

  3. 阅读3。从堆栈中获取最后一个数字(12),使12 * 10 + 3 = 123.将其推回。

  4. 大!已读取123号码。

  5. 但是,此代码示例是一堆不良做法。

    1. 一个众所周知的做法是命名堆栈函数PopPush,但不是readStack()inStack()
    2. 堆栈结构需要在读取后删除元素。 readStack()未提供此内容。
    3. 多个if而不是switch声明。
    4. 永远不要在循环中增加你的计数器。
    5. 此代码实际上不起作用,因为它不会拆分值。