Created
September 15, 2016 21:08
-
-
Save priyadarshitathagat/53292f10ec8302aa58b0a451da61468b to your computer and use it in GitHub Desktop.
Postfix to Prefix conversion in c using stacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
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.
What does your machine print for this input?
ABCDEF^/G-H*+
Mine prints this
BC+D-E*/F^GH
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
why u push '@' and also check for stack[top]=='@' ? please explain.