infix to prefix conversion

Solutions on MaxInterview for infix to prefix conversion by the best coders in the world

showing results for - "infix to prefix conversion"
Aswin
16 Jul 2019
1#include<bits/stdc++.h>
2using namespace std;
3
4int prec(char c) {
5    if(c == '^') {
6        return 3;
7    }
8    else if(c == '*' || c == '/') {
9        return 2;
10    }
11    else if(c == '+' || c =='-') {
12        return 1;
13    }
14    else {
15        return -1;
16    }
17}
18
19//--------------------------------------------------
20/*
21Algorithm -
22* Suppose your expression is 
23  -> ( a - b/c )*( a/k - l )
24  -> reverse this expression
25  -> ) l - k/a (*) c/b - a (
26  -> reverse the brackets
27  -> ( l - k/a )*( c/b - a )
28
29* If operand
30   -> print
31* If '('
32   -> push to stack
33* If ')'
34   -> pop from stack and print until '(' is found
35* If operator
36   -> pop from stack and print until an operator 
37   -> with less or equal(major change here) precedence is found
38*/
39
40string infixToPrefix(string s) {
41    stack<char> st;
42    string res;
43
44    reverse(s.begin(), s.end());
45    for (int i = 0; i < s.length(); i++)
46    {
47        if(s[i] == '(')
48          s[i] = ')';
49        else if(s[i] == ')')
50          s[i] = '(';
51    }
52    
53
54    for (int i = 0; i < s.length(); i++)
55    {
56        if(s[i] == ' ') {
57            continue;
58        }
59        else if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
60            res += s[i];
61        }
62        else if(s[i] == '(') {
63            st.push(s[i]);
64        }
65        else if(s[i] == ')') {
66            while (!st.empty() && st.top() != '(')
67            {
68                res += st.top();
69                st.pop();
70            }
71            if(!st.empty()) {
72                st.pop(); // Popping '(' here
73            }
74        }
75        else {
76            while (!st.empty() && prec(st.top()) > prec(s[i]))
77            {
78                res += st.top();
79                st.pop();
80            }
81            st.push(s[i]);
82        }
83    }
84    
85    while (!st.empty())
86    {
87       res += st.top();
88       st.pop();
89    }
90    
91    reverse(res.begin(), res.end());
92    return res;
93}
94
95int main() {
96    string exp = "a*(b-c+d)/e";
97    cout<<infixToPrefix(exp);
98    return 0;
99}