アルゴリズム/データ構造/スタック/逆ポーランド記法

逆ポーランド記法

P.31

スタックを利用した例.括弧のいらない算術記法.

reverse_polish_notation.cpp

#include <iostream>
#include "Stack.h"
using namespace std;
using namespace algo;
/**
 * 逆ポーランド記法
 * P.31
 */
void reverse_polish_notation() {
  char c;
  Stack<int> acc;
  int x;
  while (cin.get(c)) {
    x = 0;
    while (c == ' ') cin.get(c);
    if (c == '+') {
      x = acc.pop() + acc.pop();
    }
    if (c == '*') {
      x = acc.pop() * acc.pop();
    }
    while (c >= '0' && c <= '9') {
      x = 10 * x + (c - '0');
      cin.get(c);
    }
    if (c != '\n') { // この条件追加
      acc.push(x);
    }
  }
  cout << acc.pop() << endl;
}

実行結果

「5 * ((9 + 8) * (4 * 6) + 7)」を逆ポーランド記法で表すと「5 9 8 + 4 6 * * 7 + *」

> 5 9 8 + 4 6 * * 7 + * <Enter>
Ctrl+D
> 2075

Search

Apple Store(Japan)

Recommend

BUFFALO LinkStation RAID1対応 2.5インチHDD2ドライブ搭載 1.0TBモデル LS-WS1.0TGL/R1
¥ 39,332(新品)
1TBで3万台.さらに小型静音で
快適NAS生活が送れます.

view all

Twitter

Blog

Ads

ドミノ・ピザ 5%OFF!

 iTunes Store(Japan)

Logoole