-
Notifications
You must be signed in to change notification settings - Fork 139
/
Postfix to Prefix.cpp
69 lines (56 loc) · 1.12 KB
/
Postfix to Prefix.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
65
66
67
68
69
// CPP Program to convert postfix to prefix
#include <bits/stdc++.h>
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 postfix to Prefix expression
string postToPre(string post_exp)
{
stack<string> s;
// length of expression
int length = post_exp.size();
// reading from right to left
for (int i = 0; i < length; i++) {
// check if symbol is operator
if (isOperator(post_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 = post_exp[i] + op2 + op1;
// 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, post_exp[i]));
}
}
string ans = "";
while (!s.empty()) {
ans += s.top();
s.pop();
}
return ans;
}
// Driver Code
int main()
{
string post_exp = "ABC/-AK/L-*";
// Function call
cout << "Prefix : " << postToPre(post_exp);
return 0;
}