Java Assignment Convert infix to postfixSolutionTo convert i
Java Assignment
Convert infix to postfix.
Solution
To convert infix expressions to postfix, we can use the stack data structure. The stack is used to store the operators and parenthesis to apply the precedence.
For example if the input is a%b is ab%
class Stack
{
char c[]=new char[100];
int top=-1;
void push(char a)
{
try
{
c[++top]=a;
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(\"Stack full\");
System.exit(0);
}
}
char pop()
{return c[top--];
}
boolean isEmpty()
{
return (top==-1)?true:false;
}
char peak()
{
return c[top];
}
}
public class InfixToPostfix
{
static Stack expression= new Stack;
public static void main(String argv[]) throws IOException
{
String infix;
BufferedReader keyboard= new BufferedReader(new InputStreamReader(System.in));
System.out.print(\"enter the expression in infix notation\");
infix=keyboard.readLine();
System.out.println(\"The resultant postfix expression is \"+ toPostfix(infix));
}
private static String toPostfix(String infix)
{
char sym;
string postfix=\"\";
for(int i=0;i<infix.length();i++)
{
symbol=infix.charAt(i);
if(Character.isLetter(sym))
postfix=postfix+symbol;
elseif(sym==\'(\')
{
expression.push(sym);
}
else if(sym==\')\')
{
while (operators.peak()!=\'(\')
postfix=postfix+expression.pop();
expression.pop();
}
else
{
while (!expression.isEmpty() && !(expression.peak()==\'(\')&& prec(sym)<=prec(expression.peak()))
postfix=postfix+expression.pop();
expression.push(sym);
}
}
while(!expression.isEmpty())
postfix=postfix+expression.pop();
return postfix;
}
static int prec(char x)
{
if (x==\'+\'|| x==\'-\')
return 1;
if(x==\'*\'||x==\'/\'||x==\'%\')
return 2;
return 0;
}
}

