Skip to content

Instantly share code, notes, and snippets.

@priyadarshitathagat
Created September 15, 2016 21:08
Show Gist options
  • Save priyadarshitathagat/53292f10ec8302aa58b0a451da61468b to your computer and use it in GitHub Desktop.
Save priyadarshitathagat/53292f10ec8302aa58b0a451da61468b to your computer and use it in GitHub Desktop.
Postfix to Prefix conversion in c using stacks
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
# define MAX 20
char str[MAX],stack[MAX];
int top=-1;
void push(char c)
{
stack[++top]=c;
}
char pop()
{
return stack[top--];
}
void post_pre()
{
int n,i,j=0; char c[20];
char a,b,op;
printf("Enter the postfix expression\n");
gets(str);
n=strlen(str);
for(i=0;i<MAX;i++)
stack[i]='\0';
printf("Prefix expression is:\t");
for(i=n-1;i>=0;i--)
{
if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
{
push(str[i]);
}
else
{ c[j++]=str[i];
while((top!=-1)&&(stack[top]=='@'))
{
a=pop(); c[j++]=pop();
}
push('@');
}
}
c[j]='\0';
strrev(c);
printf("%s",c);
}
main()
{
post_pre();
}
@SagarSikchi
Copy link

SagarSikchi commented Nov 9, 2019

why u push '@' and also check for stack[top]=='@' ? please explain.

@priyadarshitathagat
Copy link
Author

pls try this out with an example and you would know, '@' is used as a redundant string just to have a track on when to pop items from the stack, to create a prefix expression.

@vivek-2601
Copy link

What does your machine print for this input?
ABCDEF^/G-H*+

Mine prints this
BC+D-E*/F^GH

@nightcoder26
Copy link

Can someone add an algorithm for this question like a detailed explanation. I'm having a hard time understanding it

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