-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfix_to_rpn.cpp
More file actions
57 lines (49 loc) · 1.26 KB
/
infix_to_rpn.cpp
File metadata and controls
57 lines (49 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Notacao convencional p/ notacao polonesa reversa. Operandos: a, b, ..., z.
Operadores em ordem de precedencia: ^/*-+, expressoes com parentizacao.
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 200;
void in_fix_2_reverse_polish(const string & s){
int n = s.size(), topo = 0;
int pilha[N];
string res, operators = "+-*/^";
for(int i = 0; i < n; i++){
if(isalpha(s[i])){
printf("%c", s[i]);
}
else if( s[i] == '('){
pilha[topo++] = '(';
}
else if( s[i] == ')') {
while(topo != -1){
if(pilha[topo - 1] == '('){
topo--;
break;
}
printf("%c", pilha[--topo]);
}
}
else if( operators.find(s[i]) != string::npos ) {
while(topo && operators.find(pilha[topo - 1]) != string::npos && operators.find(s[i]) <= operators.find(pilha[topo - 1]) ){
printf("%c", pilha[--topo]);
}
pilha[topo++] = s[i];
}
}
while(topo != 0){
printf("%c",pilha[--topo]);
}
puts("");
}
int main()
{
string str = "a+b";
string str2 = "(a+b)/c";
string str3 = "((a*b)-(c*d))/(e*f)";
in_fix_2_reverse_polish(str);
in_fix_2_reverse_polish(str2);
in_fix_2_reverse_polish(str3);
return 0;
}