forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix_to_prefix.cpp
64 lines (57 loc) · 1.34 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
/*
Code to convert a postfix expression to prefix expression using stacks
ALGORITHM
* Scan the postfix expression from left to right
* If the symbol is an operand, push it to the stack
* If the symbol is an operator, pop two operands from the stack
* Create a string by concatenating the two operands and the operator before them.
* Push the resultant string back to Stack
*/
#include<bits/stdc++.h>
using namespace std;
void postfixToPrefix(string s)
{
stack<string> str;
for(int i=0;i<s.length();i++)
{
if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/' || s[i]=='^')
{
string operand1=str.top();
str.pop();
string operand2=str.top();
str.pop();
//Creating the string by concatenating the operator and the operands
string prefix_part=s[i]+operand2+operand1;
str.push(prefix_part);
}
else
{
str.push(string(1,s[i]));
}
}
while(!str.empty())
{
cout<<str.top();
str.pop();
}
}
//Driver code
int main()
{
string s;
cout<<"Enter the postfix expression:\n";
cin>>s;
cout<<"Prefix expression:\n";
postfixToPrefix(s);
}
/*
Space Complexity : O(n)
Time Comlexity : O(n)
Example:
Input:
Enter the postfix expression:
ABC/-A
Output:
Prefix Expression:
A-A/BC
*/