Skip to content

Commit 95b0025

Browse files
author
Takanori MAEHARA
committed
Converting infix notation to postfix notation
1 parent 8a0715e commit 95b0025

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

string/infix_to_postfix.cc

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
//
2+
// Convert infix notation to postfix notation
3+
//
4+
// Description:
5+
// 1 * 2 + 3 * (4 + 5) <- infix notation
6+
// 1 2 * 3 4 5 + * + <- postfix notation
7+
// Postfix notation is easy to evaluate.
8+
//
9+
// Algorithm:
10+
// Shunting-yard algorithm by Dijkstra.
11+
//
12+
// Verified:
13+
// SPOJ 4: ONP - Transform the Expression
14+
//
15+
16+
#include <iostream>
17+
#include <stack>
18+
#include <vector>
19+
#include <cstdio>
20+
#include <algorithm>
21+
#include <functional>
22+
#include <sstream>
23+
24+
using namespace std;
25+
26+
string infix_to_postfix(string s) {
27+
s += '_'; // terminal symbol
28+
stringstream ss;
29+
vector<char> op = {'_'};
30+
auto rank = [](char c) { return string("(^/*-+)").find(c); };
31+
for (char c: s) {
32+
if (isalnum(c)) ss << c;
33+
else {
34+
for (; op.back() != '('; op.pop_back()) {
35+
if (rank(op.back()) >= rank(c)) break;
36+
ss << op.back();
37+
}
38+
if (c == ')') op.pop_back();
39+
else op.push_back(c);
40+
}
41+
}
42+
return ss.str();
43+
}
44+
45+
int main() {
46+
int ncase; scanf("%d", &ncase);
47+
for (int icase = 0; icase < ncase; ++icase) {
48+
char s[1024]; scanf("%s", s);
49+
printf("%s\n", infix_to_postfix(s).c_str());
50+
}
51+
}

0 commit comments

Comments
 (0)