1
Stack.java
importjava.util.*;
/**
* A LIFOstack of generic<CODE>Object</CODE>s.
*
* @author JimGlenn
* @version0.1 12/05/2005
*/
publicclassStack
{
/**
* The listthatholdsthe elementsonthisstack. The endof the
* lististhe topof the stack.
*/
private Listelements;
/**
* Createsan emptystack.
*/
publicStack()
{
elements=newArrayList();
}
/**
* Addsan itemto the top of thisstack.
*
* @param toAddthe itemto add
*/
publicvoidpush(ObjecttoAdd)
{
elements.add(toAdd);
}
/**
* Removesthe itematthe top of thisstack.
*
* @return the itemat the top of thisstack
*/
publicObjectpop()
{
returnelements.remove(elements.size() - 1);
}
2
/**
* Returnsthe itemat the top of thisstack. That itemisnot
* removed.
*
* @return the itemat the top of thisstack
*/
publicObjectpeek()
{
returnelements.get(elements.size()- 1);
}
/**
* Returnsthe numberof elementsonthisstack.
*
* @return the size of thisstack
*/
publicintsize()
{
returnelements.size();
}
}
3
Queue.java
importjava.util.*;
/**
* A FIFOqueue of generic<CODE>Object</CODE>s.
*
* @author JimGlenn
* @version0.1 12/05/2005
*/
publicclassQueue
{
/**
* The listthatholdsthe elementsonthisqueue. The frontof the
* lististhe frontof the queue.
*/
private Listelements;
/**
* Createsan emptyqueue.
*/
publicQueue()
{
elements=newLinkedList();
}
/**
* Addsan itemto the endof thisqueue.
*
* @param toAddthe itemto add
*/
publicvoidenqueue(ObjecttoAdd)
{
elements.add(toAdd);
}
/**
* Removesthe itematthe front of thisqueue.
*
* @return the itemat the frontof thisqueue
*/
publicObjectdequeue()
{
returnelements.remove(0);
}
4
/**
* Returnsthe itemat the front of thisqueue. Thatitemisnot
* removed.
*
* @return the itemat the frontof thisqueue
*/
publicObjectfirst()
{
returnelements.get(0);
}
/**
* Returnsthe numberof elementsonthisqueue.
*
* @return the size of thisqueue
*/
publicintsize()
{
returnelements.size();
}
}
5
Postfix.java
importjava.util.*;
importjava.io.*;
/**
* Anarithmeticexpressioninpostfix form.
*
* @author JimGlenn
* @version0.2 12/05/2005
* @version0.1 11/22/2004
*/
publicclassPostfix
{
private Stringexp;
/**
* Createsa postfix expressionfromthe givenprefix expression.
* Thisversiondoesnothandle errorsanddoesnot allow
* integerliterals.
*
* @param infix alegal infix expression
*/
publicPostfix(Stringinfix)
{
exp= "";
// create a queue containingthe tokensinthe infix expression;
// we do thisbecause StringTokenizerhasnoequivalentof peek
Queue queue =newQueue();
StringTokenizertok=newStringTokenizer(infix);
while (tok.hasMoreTokens())
queue.enqueue(tok.nextToken());
// create the operatorstack
Stack stack = newStack();
while (stack.size() +queue.size() >0)
{
if (queue.size()==0)
exp= exp+ stack.pop() +" ";
else if (isIdentifier((String)(queue.first())))
exp= exp+ queue.dequeue()+" ";
else if (queue.first().equals("("))
stack.push(queue.dequeue());
else if (stack.size()==0)
6
stack.push(queue.dequeue());
else if (getPrecedence((String)(queue.first()))
> getPrecedence((String)(stack.peek())))
stack.push(queue.dequeue());
else if (stack.peek().equals("(")
&& queue.first().equals(")"))
{
stack.pop();
queue.dequeue();
}
else
exp= exp+ stack.pop() +" ";
}
}
/**
* Precedence levelsforarithmeticoperatorsandparentheses.
* Levelsare spacedoutto make it easiertoadd operatorswith
* in betweenprecedences.
*/
private staticfinal intADDITIVE= 0;
private staticfinal intMULTIPLICATIVE= 10;
private staticfinal intPARENTHESES= -10;
/**
* Returnsthe precedence of the givenoperator.
*
* @param op an operatoror parenthesis
* @return the precedence of the givenoperator.
*/
private staticintgetPrecedence(Stringop)
{
if (op.equals("+") ||op.equals("-"))
returnADDITIVE;
else if (op.equals("*") ||op.equals("/"))
returnMULTIPLICATIVE;
else if (op.equals("(") ||op.equals(")"))
returnPARENTHESES;
else
throw newIllegalArgumentException();
}
/**
* Determinesif the givenstringisanidentifier.
*
* @param id a string
* @return true iff the givenstringisan identifier
*/
7
private staticbooleanisIdentifier(Stringid)
{
returnCharacter.isJavaIdentifierStart(id.charAt(0));
}
/**
* Returnsa stringrepresentationof thisexpression.
*
* @return a stringrepresentationof thisexpression.
*/
publicStringtoString()
{
returnexp;
}
publicstaticvoidmain(String[] args) throwsIOException
{
BufferedReaderin
= newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enteralegal infix expression:");
System.out.println(newPostfix(in.readLine()));
}
}

Posfix

  • 1.
    1 Stack.java importjava.util.*; /** * A LIFOstackof generic<CODE>Object</CODE>s. * * @author JimGlenn * @version0.1 12/05/2005 */ publicclassStack { /** * The listthatholdsthe elementsonthisstack. The endof the * lististhe topof the stack. */ private Listelements; /** * Createsan emptystack. */ publicStack() { elements=newArrayList(); } /** * Addsan itemto the top of thisstack. * * @param toAddthe itemto add */ publicvoidpush(ObjecttoAdd) { elements.add(toAdd); } /** * Removesthe itematthe top of thisstack. * * @return the itemat the top of thisstack */ publicObjectpop() { returnelements.remove(elements.size() - 1); }
  • 2.
    2 /** * Returnsthe itematthe top of thisstack. That itemisnot * removed. * * @return the itemat the top of thisstack */ publicObjectpeek() { returnelements.get(elements.size()- 1); } /** * Returnsthe numberof elementsonthisstack. * * @return the size of thisstack */ publicintsize() { returnelements.size(); } }
  • 3.
    3 Queue.java importjava.util.*; /** * A FIFOqueueof generic<CODE>Object</CODE>s. * * @author JimGlenn * @version0.1 12/05/2005 */ publicclassQueue { /** * The listthatholdsthe elementsonthisqueue. The frontof the * lististhe frontof the queue. */ private Listelements; /** * Createsan emptyqueue. */ publicQueue() { elements=newLinkedList(); } /** * Addsan itemto the endof thisqueue. * * @param toAddthe itemto add */ publicvoidenqueue(ObjecttoAdd) { elements.add(toAdd); } /** * Removesthe itematthe front of thisqueue. * * @return the itemat the frontof thisqueue */ publicObjectdequeue() { returnelements.remove(0); }
  • 4.
    4 /** * Returnsthe itematthe front of thisqueue. Thatitemisnot * removed. * * @return the itemat the frontof thisqueue */ publicObjectfirst() { returnelements.get(0); } /** * Returnsthe numberof elementsonthisqueue. * * @return the size of thisqueue */ publicintsize() { returnelements.size(); } }
  • 5.
    5 Postfix.java importjava.util.*; importjava.io.*; /** * Anarithmeticexpressioninpostfix form. * *@author JimGlenn * @version0.2 12/05/2005 * @version0.1 11/22/2004 */ publicclassPostfix { private Stringexp; /** * Createsa postfix expressionfromthe givenprefix expression. * Thisversiondoesnothandle errorsanddoesnot allow * integerliterals. * * @param infix alegal infix expression */ publicPostfix(Stringinfix) { exp= ""; // create a queue containingthe tokensinthe infix expression; // we do thisbecause StringTokenizerhasnoequivalentof peek Queue queue =newQueue(); StringTokenizertok=newStringTokenizer(infix); while (tok.hasMoreTokens()) queue.enqueue(tok.nextToken()); // create the operatorstack Stack stack = newStack(); while (stack.size() +queue.size() >0) { if (queue.size()==0) exp= exp+ stack.pop() +" "; else if (isIdentifier((String)(queue.first()))) exp= exp+ queue.dequeue()+" "; else if (queue.first().equals("(")) stack.push(queue.dequeue()); else if (stack.size()==0)
  • 6.
    6 stack.push(queue.dequeue()); else if (getPrecedence((String)(queue.first())) >getPrecedence((String)(stack.peek()))) stack.push(queue.dequeue()); else if (stack.peek().equals("(") && queue.first().equals(")")) { stack.pop(); queue.dequeue(); } else exp= exp+ stack.pop() +" "; } } /** * Precedence levelsforarithmeticoperatorsandparentheses. * Levelsare spacedoutto make it easiertoadd operatorswith * in betweenprecedences. */ private staticfinal intADDITIVE= 0; private staticfinal intMULTIPLICATIVE= 10; private staticfinal intPARENTHESES= -10; /** * Returnsthe precedence of the givenoperator. * * @param op an operatoror parenthesis * @return the precedence of the givenoperator. */ private staticintgetPrecedence(Stringop) { if (op.equals("+") ||op.equals("-")) returnADDITIVE; else if (op.equals("*") ||op.equals("/")) returnMULTIPLICATIVE; else if (op.equals("(") ||op.equals(")")) returnPARENTHESES; else throw newIllegalArgumentException(); } /** * Determinesif the givenstringisanidentifier. * * @param id a string * @return true iff the givenstringisan identifier */
  • 7.
    7 private staticbooleanisIdentifier(Stringid) { returnCharacter.isJavaIdentifierStart(id.charAt(0)); } /** * Returnsastringrepresentationof thisexpression. * * @return a stringrepresentationof thisexpression. */ publicStringtoString() { returnexp; } publicstaticvoidmain(String[] args) throwsIOException { BufferedReaderin = newBufferedReader(newInputStreamReader(System.in)); System.out.println("Enteralegal infix expression:"); System.out.println(newPostfix(in.readLine())); } }