forked from wbhima/CodeforALL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prefix to PostFix.cpp
64 lines (54 loc) · 1.09 KB
/
Prefix to PostFix.cpp
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
// CPP Program to convert prefix to postfix
#include <iostream>
#include <stack>
using namespace std;
// function to check if character is operator or not
bool isOperator(char x)
{
switch (x) {
case '+':
case '-':
case '/':
case '*':
return true;
}
return false;
}
// Convert prefix to Postfix expression
string preToPost(string pre_exp)
{
stack<string> s;
// length of expression
int length = pre_exp.size();
// reading from right to left
for (int i = length - 1; i >= 0; i--)
{
// check if symbol is operator
if (isOperator(pre_exp[i]))
{
// pop two operands from stack
string op1 = s.top();
s.pop();
string op2 = s.top();
s.pop();
// concat the operands and operator
string temp = op1 + op2 + pre_exp[i];
// Push string temp back to stack
s.push(temp);
}
// if symbol is an operand
else {
// push the operand to the stack
s.push(string(1, pre_exp[i]));
}
}
// stack contains only the Postfix expression
return s.top();
}
// Driver Code
int main()
{
string pre_exp = "*-A/BC-/AKL";
cout << "Postfix : " << preToPost(pre_exp);
return 0;
}