import java.util.Scanner;
public class InFixToPostFix
{
int Priority(char TopSym,char Sym)
{
if(TopSym=='(')
return 0;
if(Sym=='(')
return 0;
if(Sym==')')
return 1;
if((TopSym=='*'||TopSym=='/'))
return 1;
if((TopSym== '+'||TopSym=='-')&&(Sym=='-'||Sym=='+'))
return 1;
if((TopSym== '+'||TopSym=='-')&&(Sym=='*'||Sym=='/'))
return 0;
else
return 1;
}
boolean isOperand(char Sym)
{
if(Sym>='0'&& Sym<='9')
return true;
else
return false;
}
void Convert(char infix[],char postfix[])
{
Stack_Char sc=new Stack_Char();
int inpos,und=1,outpos=0;
char TopSym='+',Sym;
for(inpos=0;inpos<infix.length;inpos++)
{
Sym=infix[inpos];
if(isOperand(Sym))
postfix[outpos++]=Sym;
else
{
if (sc.isEmpty()==true)
und=1;
else
{
und=0;
TopSym=(char)sc.Pop();
}
while(und==0 && Priority(TopSym,Sym)==1)
{
postfix[outpos++]=TopSym;
if (sc.isEmpty()==true)
und=1;
else
{
und=0;
TopSym=(char)sc.Pop();
}
}
if(und==0)
sc.Push(TopSym);
if(und==1||(Sym!=')'))
sc.Push(Sym);
else
TopSym=(char)sc.Pop();
}
}
while(sc.isEmpty()==false)
postfix[outpos++]=(char)sc.Pop();
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
InFixToPostFix i=new InFixToPostFix();
String Infix;
char postfix[]=new char[30];
System.out.println("Enter Infix Equation");
Infix=in.nextLine();
i.Convert(Infix.toCharArray(), postfix);
System.out.print("Postfix Expression = ");
System.out.println(postfix);
}
}
No comments:
Post a Comment