-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinfix2postfix.cpp
More file actions
92 lines (89 loc) · 1.89 KB
/
infix2postfix.cpp
File metadata and controls
92 lines (89 loc) · 1.89 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
87
88
89
90
91
92
/*
Author: Saurabh Odhyan
infix to postfix conversion and evaluation of the postfix expression
*/
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int precedence(char ch)
{
switch(ch)
{
case '^' : return 5;
case '/' : return 4;
case '*' : return 4;
case '+' : return 3;
case '-' : return 3;
default : return 0;
}
}
bool isOperand(char ch)
{
if(ch=='(' || ch==')' || ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='^') return false;
return true;
}
int eval(int x,int y,char ch){
switch(ch){
case '^' : return x^y;
case '/' : return x/y;
case '*' : return x*y;
case '+' : return x+y;
case '-' : return x-y;
default : return 1;
}
}
int evalPostfix(string str){
stack<char> S;
for(int i=0;i<str.size();i++){
if(isOperand(str[i])){
S.push(str[i]-'0');
}else{
int y=S.top(); S.pop();
int x=S.top(); S.pop();
int z=eval(x,y,str[i]);
S.push(z);
}
}
return S.top();
}
int main()
{
string str; //infix expression as input
while(cin>>str)
{
stack<char> S;
string res=""; //postfix expression as output
for(int i=0;i<str.size();i++)
{
if(isOperand(str[i]))
res+=str[i];
else if(str[i]=='('){
S.push(str[i]);
}
else if(str[i]==')'){
while(S.top()!='('){
res+=S.top();
S.pop();
}
S.pop();
}
else if(S.empty() || precedence(str[i])>precedence(S.top())){
S.push(str[i]);
}
else{
while(!S.empty() && precedence(str[i])<=precedence(S.top())){
res+=S.top();
S.pop();
}
S.push(str[i]);
}
}
while(!S.empty()){
res+=S.top();
S.pop();
}
cout<<"Postfix expression: "<<res<<endl;
cout<<"Value: "<<evalPostfix(res)<<endl;
}
}