Infix to Prefix- First transforming reverse of infix to postfix and reversing the result to get prefix.
However the problem lies in reversing of the postfix expression. I suspect the problem lies with using pointers. I tried reversing using other way and it worked.
But I can't seem to understand why the problem is arising.
Output:
c*b+a //Reverse of given infix expression
cb*a+ //Postfix of the reversed infix expression
+a*a+ //Prefix: Problem
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
Method declarations
....
*/
void main()
{
char infix[] = "a+b*c";
char* reverse = rev(exp);
printf("%s\n", reverse);
char* postfix = inToPost(reverse);
printf("%s\n", postfix);
char* prefix= rev(postfix);
printf("%s", prefix);
}
char* rev(char* ptr1)
{
char rev[strlen(ptr1)+1];
char *temp = ptr1;
int i =0;
while(*ptr1!='\0')
{
ptr1++;
}
do
{
rev[i++] = *--ptr1;
}while(ptr1!=temp);
rev[i] = '\0';
ptr1 = rev;
return ptr1;
}
char* inToPost(char *ptr)
{
char post[strlen(ptr)+1];
int i =0;
while(*ptr!='\0')
{
char ch = *ptr;
if(isOperand(ch))
{
post[i++]=ch;
//printf("%c",ch);
}
else if(isOperator(ch))
{
while(!isEmpty() && !isOpenP(peek()) && getPrec(peek())>=getPrec(ch))
{
post[i++]=peek();
//printf("%c", peek());
pop();
}
push(ch);
}
else if(isOpenP(ch))
{
push(ch);
}
else if(isCloseP(ch))
{
while(!isEmpty() && !isOpenP(peek()))
{
post[i++]=peek();
//printf("%c", peek());
pop();
}
pop();
}
ptr++;
}
while(!isEmpty())
{
post[i++]=peek();
//printf("%c", peek());
pop();
}
post[i] = '\0';
ptr = post;
return ptr;
}
/*
Method definitions
*/