■ 逆ポーランド記法
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
Referrer
1.028 sec
- 3: http://www.google.com/search?hl=ja&lr=lang_ja&ie=UTF-8&oe=UTF-8&q=%E9%80%86%E3%83%9D%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89%E6%95%B4%E5%88%97&num=50
- 2: http://www.google.com/search?q=%E9%80%86%E3%83%9D%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89%E3%80%80%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0&ie=utf-8&oe=utf-8&aq=t&rls=org.debian:ja:unofficial&client=iceweasel-a
- 2: http://www.google.co.jp/search?hl=ja&lr=&q=%E3%83%9D%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89%E8%A8%98%E6%B3%95+%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0&suggest=2&sa=X&oi=cjkrefinements&resnum=1&ct=result&cd=3
- 2: http://www.google.co.jp/search?hl=ja&q=%E9%80%86%E3%83%9D%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89%E3%80%80%E3%82%B9%E3%82%BF%E3%83%83%E3%82%AF&lr=
- 2: http://www.google.co.jp/search?q=%E9%80%86%E3%83%9D%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89%E8%A8%98%E6%B3%95%E3%80%80%26%26&hl=ja&start=10&sa=N


