【问题标题】:Calculating in Polish notation用波兰记数法计算
【发布时间】:2015-07-03 08:27:02
【问题描述】:

我有这个代码:

#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'));

【问题讨论】:

  • stack 这样一个奇怪的实现。调用方法pushpop 而不是readStackinStack 是一种众所周知的做法。此外,pop 应该自动删除最后一个元素,而无需调用 outOfStack
  • 如果我错了,请纠正我,但这应该不起作用:我们推入堆栈的操作结果(不删除第二个操作数)然后丢弃?!
  • polish.inStack(10 * el + (a[i++]-'0')); 如果您假设 stack&lt;int&gt;::readStack() 返回 int 这意味着您传递了 10 * 该调用的结果 + 作为输入给 stack&lt;int&gt;::inStack(); 的下一个字符
  • @YeldarKurmangaliyev 看起来像一个带有非标准名称的标准接口 - inStackpushreadStacktopoutOfStackpop

标签: c++ stack notation


【解决方案1】:

看起来它是一个读取和计算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 数字(如 '3')转换为整数 3。

最初,我们的堆栈中有一个零。 例如,如果您有“123”,它将以这种方式逐个字符地读取它们:

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

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

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

  4. 太棒了!已读取123号。

但是,这个代码示例是一堆不好的做法。

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

【讨论】:

  • 通常还有peek ,它正在做readStack似乎正在做的事情。
猜你喜欢
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
相关资源
最近更新 更多