Skip to content

Commit 94d30c7

Browse files
authored
added postfix to prefix conversion in cpp
1 parent 2b97ead commit 94d30c7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

C++/Postfix_to_Prefix_Conversion.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
bool isOperator(char x)
4+
{
5+
switch (x) {
6+
case '+':
7+
case '-':
8+
case '/':
9+
case '*':
10+
return true;
11+
}
12+
return false;
13+
}
14+
string postToPre(string post_exp)
15+
{
16+
stack<string> s;
17+
int length = post_exp.size();
18+
for (int i = 0; i < length; i++) {
19+
if (isOperator(post_exp[i])) {
20+
string op1 = s.top();
21+
s.pop();
22+
string op2 = s.top();
23+
s.pop();
24+
string temp = post_exp[i] + op2 + op1;
25+
s.push(temp);
26+
}
27+
else {
28+
s.push(string(1, post_exp[i]));
29+
}
30+
}
31+
32+
string ans = "";
33+
while (!s.empty()) {
34+
ans += s.top();
35+
s.pop();
36+
}
37+
return ans;
38+
}
39+
int main()
40+
{
41+
string post_exp = "ABC/-AK/L-*";
42+
cout << "Prefix : " << postToPre(post_exp);
43+
return 0;
44+
}

0 commit comments

Comments
 (0)