-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.cpp
More file actions
54 lines (51 loc) · 1.2 KB
/
Copy pathpostfix.cpp
File metadata and controls
54 lines (51 loc) · 1.2 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
#include<bits/stdc++.h>
using namespace std;
int precedence(char a)
{
if(a == '^') return 3;
else if(a == '*' || a == '/' || a == '%') return 2;
else if(a == '+' || a == '-') return 1;
else return -1;
}
string topostfix(string infix)
{
stack<char> st;
st.push('(');
string result;
infix = infix +')';
int len = infix.size();
for(int i = 0; i<len; i++)
{
if(isalnum(infix[i]))///checking if it is operand
result+=infix[i];
else if(infix[i] == '(')
st.push('(');
else if(infix[i] == ')')
{
while(st.top()!= '(')
{
result+=st.top();
st.pop();
}
if(st.top() == '(')
st.pop();
}
else ///checking if it is operator
{
while(precedence(infix[i])<=precedence(st.top()))
{
result+=st.top();
st.pop();
}
st.push(infix[i]);
}
}
return result;
}
int main()
{
string infix;
cin >> infix;
cout << "The Postfix : " << topostfix(infix) << endl;
return 0;
}