Friday, 20 December 2019

Java program for infix-postfix conversion

import java.util.*;
class Infix_Postfix
{
String infix;
char stack[];
int top; String postfix;
Infix_Postfix()
{
stack =new char[100];
top=-1;
}
public void get()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the infix expression and keep a gap between the symbols");
infix=sc.nextLine();
}
public void Push(char ch)
{
if(top>=99)
{
System.out.println("Stack overflow");
return;
}
stack[++top]=ch;
}
public char pop()
{
if(top==-1)
{
System.out.println("Stack underflow");
return '@';
}
return stack[top--];
}
public int precedence(char ch)
{
switch(ch)
{
case '^':return 3;
case '*':
case '/':
case '%':return 2;
case '+':
case '-':return 1;
default:return 0;
}
}
public boolean isDigit(char ch)
{
if(ch>='0' && ch<='9')
return true;
return false;
}
public void convert()
{
get();
char ch;
infix=infix+" ) ";
Push('(');
String wd="";
postfix="";
System.out.println(infix);
for(int i=0;i<infix.length();i++)
{
if(isDigit(wd.charAt(0)))
postfix+=wd+" ";
else if(wd.charAt(0)=='(')
Push('(');
else if(stack[top]=='(')
{
while(true)
{
ch=pop();
if(ch=='(')
break;
postfix+=ch+" ";
}
wd="";
}
else
wd=wd+infix.charAt(i);
}
}
public void display()
{
System.out.println("The result is " + postfix);
}
}

No comments:

Post a Comment

Convey your thoughts to authors.