1Best Solution
2-------------------------------------------------------------------
3#include<bits/stdc++.h>
4using namespace std;
5
6int prec(char c) {
7 if(c == '^') {
8 return 3;
9 }
10 else if(c == '*' || c == '/') {
11 return 2;
12 }
13 else if(c == '+' || c =='-') {
14 return 1;
15 }
16 else {
17 return -1;
18 }
19}
20
21string infixToPostfix(string s) {
22 stack<char> st;
23 string res;
24
25 for (int i = 0; i < s.length(); i++)
26 {
27 if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
28 res += s[i];
29 }
30 else if(s[i] == '(') {
31 st.push(s[i]);
32 }
33 else if(s[i] == ')') {
34 while (!st.empty() && st.top() != '(')
35 {
36 res += st.top();
37 st.pop();
38 }
39 if(!st.empty()) {
40 st.pop(); // Popping '(' here
41 }
42 }
43 else {
44 while (!st.empty() && prec(st.top()) >= prec(s[i]))
45 {
46 res += st.top();
47 st.pop();
48 }
49 st.push(s[i]);
50 }
51 }
52
53 while (!st.empty())
54 {
55 res += st.top();
56 st.pop();
57 }
58
59 return res;
60}
61
62int main() {
63 string exp = "a+b*(c^d-e)^(f+g*h)-i";
64 cout<<infixToPostfix(exp);
65 return 0;
66}
1Begin
2 initially push some special character say # into the stack
3 for each character ch from infix expression, do
4 if ch is alphanumeric character, then
5 add ch to postfix expression
6 else if ch = opening parenthesis (, then
7 push ( into stack
8 else if ch = ^, then //exponential operator of higher precedence
9 push ^ into the stack
10 else if ch = closing parenthesis ), then
11 while stack is not empty and stack top ≠ (,
12 do pop and add item from stack to postfix expression
13 done
14
15 pop ( also from the stack
16 else
17 while stack is not empty AND precedence of ch <= precedence of stack top element, do
18 pop and add into postfix expression
19 done
20
21 push the newly coming character.
22 done
23
24 while the stack contains some remaining characters, do
25 pop and add to the postfix expression
26 done
27 return postfix
28End