/*----Program to Convert Infix Expression into PostFix Expression---*/
/* Theory :In conversion of infix expression to postfix expression infix expression a+b in this expression a & b are operand and + is a opertor while converting a will be copied to new expression callsed as postfix and after that + will be copied to the stack the b will be copied to postfix expression and as infix expression has no more elements all the element of stack will copied to postfix expression*/
import java.io.*;
class MyStack
{
char []a;
int top;
MyStack()
{
a=new char[5];
top=-1;
}
MyStack(int size)
{
a=new char[size];
top=-1;
}
boolean empty() // Empty Method
{
return (top==-1)?true:false;
}
void push(char ele)
{
if(top<a.length-1)
a[++top]=ele;
else
System.out.println("\n\t\t Stack OverFlow");
} // End Of PUSH Method
char pop()
{
if(!empty())
return a[top--];
else
return (char)-1;
} // End Of POP Method
} //End Of MyStack Class
class In2PostExample
{
String exp;
In2PostExample()
{
exp=new String("a+b");
}
In2PostExample(String s)
{
exp=new String (s);
}
int precedence(char a) //Start of precedent method
{
switch(a)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
}
return 0;
} //End of precedent method
/* --------------------------------------Start of convert method--------------------------------------------*/
String convert()
{
char[] pexpr=new char[exp.length()+1];
char c,sc='\0';
int i,j;
MyStack st=new MyStack(exp.length());
for(i=0,j=0;i<exp.length();i++)
{
c=exp.charAt(i);
switch(c)
{
case '+':
case '-':
case '*':
case '/':
/*Checking the precedence of operator in stack and the operator that has been taken from infix expression*/
while(!st.empty() && precedence(sc=st.pop())>=precedence(c))
pexpr[j++]=sc;
st.push(sc);
st.push(c);
break;
case '(':
st.push(c);
break;
case ')':
while((sc=st.pop())!='(')
pexpr[j++]=sc;
break;
default:
pexpr[j++]=c;
}
}
while(!st.empty())
if((sc=st.pop())!='(')
pexpr[j++]=sc;
return (new String(pexpr));
}
public static void main(String args[])throws IOException //Start of main method
{
System.out.print("\n\t\t Enter the Infix Expression:: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
In2PostExample infix=new In2PostExample(str);
String p=infix.convert();
System.out.println("\n\t\t The Postfix String is:: "+p); //Printing Postfix string
} //End of main method
} //End of main class
***** OUTPUT ******
Comments
Post a Comment