-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathInfixToPostfix.cpp
More file actions
63 lines (58 loc) · 1.38 KB
/
InfixToPostfix.cpp
File metadata and controls
63 lines (58 loc) · 1.38 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
using namespace std;
#include<iostream>
#include<stack>
int prec(char c){
if(c == '^')
return 3;
else if( c== '*' || c == '/')
return 2;
else if( c== '+' || c=='-')
return 1;
else{
return -1;
}
}
string postfix(string str){
string result="";
stack<char> S;
for(int i=0;i<str.length();i++){
if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0' && str[i] <= '9')){
result+=str[i];
}
else if(str[i]=='(')
S.push(str[i]);
else if(str[i]==')'){
while(S.top()!='('){
result +=S.top();
S.pop();
}
S.pop();
}
else{
if(S.empty())
S.push(str[i]);
else if(prec(str[i])>prec(S.top())){
S.push(str[i]);
}
else{
while(!S.empty() && (prec(str[i])<=prec(S.top()))){
result+=S.top();
S.pop();
}
S.push(str[i]);
}
}
}
while(!S.empty()){
result+=S.top();
S.pop();
}
return result;
}
int main(){
string str;
cout<<"enter the infix expression: ";
cin>>str;
cout<<"the postfix expression of the given infix expression is :"<< postfix(str);
return 0;
}