-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathsuffix 2 prefix
More file actions
86 lines (77 loc) · 1.72 KB
/
suffix 2 prefix
File metadata and controls
86 lines (77 loc) · 1.72 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <stack>
using namespace std;
bool Cprec(char c){
if(c == '+' || c == '-' || c == '*' || c == '/'){
return true;
}
else{
return false;
}
}
int prec(char c){
if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
string Infix2Suffix(stack<char> s,string infix) {
string postfix;
for(int i=0;i<infix.length();i++){
if((infix[i] >= 'a' && infix [i] <= 'z') ||
(infix[i] >= 'A' && infix [i] <= 'Z' ) ||
(infix[i] >= '0' && infix [i] <= '9')){
postfix += infix[i];
}
else if(infix[i] == '('){
s.push(infix[i]);
}
else if(infix[i] == ')'){
while((s.top()!='(') && (!s.empty())){
char temp = s.top();
postfix += temp;
s.pop();
}
}
else if(Cprec(infix[i])){
if(s.empty()){
s.push(infix[i]);
}
else{
if(prec(infix[i])>prec(s.top())){
s.push(infix[i]);
}
else{
while((!s.empty()) && (prec(infix[i])<=prec(s.top()))){
char temp = s.top();
postfix += temp;
s.pop();
}
s.push(infix[i]);
}
}
}
}
while(!s.empty()){
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
char ans[2];
string exp, postfix;
do{
cout << "Put the infix expression: " << endl;
getline (cin,exp);
stack<char> stack;
postfix = Infix2Suffix(stack, exp);
cout << "The postfix expression: " << postfix << endl;
cout << "Take another data? (Y/N) ";
cin >> ans;
cin.ignore();
}while(ans[0] == 'Y' || ans[0] == 'y');
return 0;
}