Write a program in JAVA to Converts Infix equation into Postfix form.
Program Code:
import java.io.*;
import java.util.*;
class charstack
{
int top,size;
char stack[],ele;
charstack(int n)
{
size=n;
top=-1;
stack=new char[n];
}
void push(char x)
{
ele=x;
if(!isfull())
{
stack[++top]=ele;
}
else
System.out.println("stack is full");
}
char pop()
{
if(!isempty())
{
return stack[top--];
}
else
{
System.out.println("stack is empty");
return 'a';
}
}
boolean isempty()
{
if(top==-1)
return true;
else
return false;
}
boolean isfull()
{
if(top>size)
return true;
else
return false;
}
void display()
{
if(!isempty())
System.out.println("="+stack[top]);
else
System.out.println("stack is empty");
}
char peek()
{
return stack[top];
}
}
class InfixToPostfix
{
charstack cs;
char pf[];
InfixToPostfix()
{
cs=new charstack(50);
pf=new char[50];
}
boolean iop(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='^'||op=='%')
return true;
else
return false;
}
int prec(char op)
{
if(op=='+'||op=='-')
return 1;
else if(op=='/'||op=='*')
return 2;
else if(op=='%'||op=='^')
return 3;
return 0;
}
void infixtop(String infix)
{
char isym;
int j=0;
char ir[]=infix.toCharArray();
for(int i=0;i<ir.length;i++)
{
isym=ir[i];
if(!iop(isym))
{
pf[j]=isym;
j++;
}
else
{
if(isym=='('||cs.isempty())
cs.push(isym);
else if(isym==')')
{
while(cs.peek()!='(')
{
pf[j]=cs.pop();
j++;
}
char v=cs.pop();
}
else if(cs.isempty())
cs.push(isym);
else if(cs.isempty()||cs.peek()=='('||(prec(cs.peek())<prec(isym)))
cs.push(isym);
else
{
while((!cs.isempty())&&(cs.peek()!='(')&&prec(cs.peek())>=prec(isym))
{
pf[j]=cs.pop();
j++;
}
cs.push(isym);
}
}
}
while(!cs.isempty())
{
pf[j]=cs.pop();
j++;
}
}
void display1()
{
for(int i=0;i<pf.length-1;i++)
System.out.print(pf[i]);
}
public static void main(String args[])throws Exception
{
InfixToPostfix ob=new InfixToPostfix();
Scanner r=new Scanner(System.in);
System.out.println("Enter any equation:");
String s=r.nextLine();
ob.infixtop(s);
ob.display1();
}
}
Output:
Enter any equation:
a+b*c-d
abc*+d
Post A Comment:
0 comments: