Pages

Friday, October 25, 2013

INFIX TO POSTFIX CONVERSION USING STACK.

/*

TOPIC: INFIX TO POSTFIX.
DATE:9/8/2012

*/
import java.util.*;
import java.io.*;
class stack
{
int top;char a[];
stack(int n)
{
top=-1;
a=new char[n];
}
void push(char c)
{
if(top==a.length-1)
System.out.println("stack full");
else a[++top]=c;
}
char pop() throws Exception
{
if (top==-1) throw new Exception("stack empty");
else return a[top--];
}
boolean empty()
{
return top==-1;
}
char peek() throws Exception
{
if(empty())
throw new Exception();
else
return a[top];
}
void display() throws Exception
{
if(empty())
throw new Exception();
else
{
for(int i=0;i<+top;i++)
{
System.out.print(a[i]+" ");
}

}}
int compare(char c)
{
switch (c)
{
case '$':
case '^':return 4;
case '*':
case '/':return 3;
case '+':
case '-':return 2;
case '(':
case ')':return 1;
}
return 0;
}
}
class demo
{
public static void main(String arg[])throws Exception
{
Scanner sc=new Scanner (System.in);
stack s=new stack(10);
System.out.println("enter infix exp");
String infix=sc.next();

String post=" ";
char a[]=infix.toCharArray();
for(int i=0;i<a.length;i++)
{
if (Character.isLetterOrDigit(a[i]))
post+=a[i];
else
if(s.empty()||a[i]=='('||s.compare(a[i])>s.compare(s.peek())||a[i]=='^')
s.push(a[i]);
else if(a[i]==')')
{
while (s.peek()!='(')
post+=s.pop();
s.pop();
}

else
{
while(!s.empty()&&s.compare(a[i])>=s.compare(s.peek()))
post+=s.pop();
s.push(a[i]);
}
}
while(!s.empty())
{
post+=s.pop();
System.out.print(post);
}
}
}
/*
OUTPUT:
enter infix exp
a*(b-c)/d

abc-*d/
*/

No comments:

Post a Comment