Skip to content

Instantly share code, notes, and snippets.

@vaishaks
Created August 31, 2012 13:38
Show Gist options
  • Save vaishaks/3552757 to your computer and use it in GitHub Desktop.
Save vaishaks/3552757 to your computer and use it in GitHub Desktop.
C++ code to convert postfix expression to prefix
#include <iostream>
#include <cstring>
#include <stack>
#include <algorithm>
#define flag '#'
using namespace std;
bool isOperator(char c)
{
if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^' || c=='$')
return true;
else
return false;
}
int main()
{
stack<char> stk;
char postfix[30], prefix[30];
int j=0,len;
cout<<"Input a postfix expression: ";
cin>>postfix;
len = strlen(postfix);
for(int i=len-1;i>=0;i--)
{
if(isOperator(postfix[i]))
stk.push(postfix[i]);
else
{
prefix[j++] = postfix[i];
while(!stk.empty() && stk.top()==flag)
{
stk.pop();
prefix[j++] = stk.top();
stk.pop();
}
stk.push(flag);
}
}
prefix[j] = 0;
reverse(prefix, prefix + len);
cout<<"The prefix expression is: "<<prefix;
return 0;
}
@dhtzl
Copy link

dhtzl commented May 16, 2019

comfortable...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment