CS 202 - Computer Science II - Spring 2007
Infix to Postfix


Loyola College > Department of Computer Science > Dr. James Glenn > CS 202 > Examples and Lecture Notes > Infix to Postfix

You can start with this incomplete version of the code.

Postfix.java

import java.util.*;
import java.io.*;

/**
 * An arithmetic expression in postfix form.
 *
 * @author Jim Glenn
 * @version 0.1 11/22/2004
 */

public class Postfix
{
    private String exp;

    /**
     * Creates a postfix expression from the given prefix expression.
     * This version does not handle errors and does not allow
     * integer literals.
     *
     * @param infix a legal infix expression
     */

    public Postfix(String infix)
    {
	exp = "";

	Stack pendingOps = new Stack();

	StringTokenizer tok = new StringTokenizer(infix);

	while (tok.hasMoreTokens())
	    {
		String token = tok.nextToken();

		if (!isOperator(token))
		    exp = exp + token + " ";
		else
		    {
			if (token.equals("("))
			    pendingOps.push(token);
			else if (pendingOps.size() == 0)
			    pendingOps.push(token);
			else if (token.equals(")"))
			    {
				while (!pendingOps.peek().equals("("))
				    exp = exp + pendingOps.pop() + " ";
			    }
			else
			    {
				while (pendingOps.size() > 0
				       && getPrecedence((String)pendingOps.peek()) >= getPrecedence(token))
				    exp = exp + pendingOps.pop() + " ";

				pendingOps.push(token);
			    }

		    }
	    }
	
	while (pendingOps.size() > 0)
	    exp = exp + pendingOps.pop() + " ";
    }

    /**
     * Precedence levels for arithmetic operators and parentheses.
     * Levels are spaced out to make it easier to add operators with
     * in between precedences.
     */

    private static final int ADDITIVE = 0;
    private static final int MULTIPLICATIVE = 10;
    private static final int PARENTHESES = -10;

    /**
     * Returns the precedence of the given operator.
     *
     * @param op an operator or parenthesis
     * @return the precedence of the given operator.
     */

    private static int getPrecedence(String op)
    {
	if (op.equals("+") || op.equals("-"))
	    return ADDITIVE;
	else if (op.equals("*") || op.equals("/"))
	    return MULTIPLICATIVE;
	else if (op.equals("(") || op.equals(")"))
	    return PARENTHESES;
	else
	    throw new IllegalArgumentException();
    }    

    /**
     * Determines if the given string is an identifier.
     *
     * @param id a string
     * @return true iff the given string is an identifier
     */

    private static boolean isIdentifier(String id)
    {
	return Character.isJavaIdentifierStart(id.charAt(0));
    }

    /**
     * Determines if the given string is an integer literal.
     *
     * @param num a string
     * @return true iff that string is an integer literal
     */

    private static boolean isLiteral(String num)
    {
	return (num.charAt(0) >= '0' && num.charAt(0) <= '9');
    }

    /**
     * Determines if the given string is an operator.
     *
     * @param op a string
     * @return true iff that string is an operator
     */

    public static boolean isOperator(String op)
    {
	return (op.length() == 1 && "()*-/+".indexOf(op.charAt(0)) != -1);
    }

    /**
     * Returns a string representation of this expression.
     *
     * @return a string representation of this expression.
     */

    public String toString()
    {
	return exp;
    }

    public static void main(String[] args) throws IOException
    {
	BufferedReader in
	    = new BufferedReader(new InputStreamReader(System.in));

	System.out.println("Enter a legal infix expression:");
	System.out.println(new Postfix(in.readLine()));
    }
}

Stack.java

import java.util.*;

/**
 * A LIFO stack of generic <CODE>Object</CODE>s.
 *
 * @author Jim Glenn
 * @version 0.1 12/05/2005
 */

public class Stack
{
    /**
     * The list that holds the elements on this stack.  The end of the
     * list is the top of the stack.
     */

    private List elements;

    /**
     * Creates an empty stack.
     */

    public Stack()
    {
	elements = new LinkedList();
    }

    /**
     * Adds an item to the top of this stack.
     *
     * @param toAdd the item to add
     */

    public void push(Object toAdd)
    {
	elements.add(toAdd);
    }

    /**
     * Removes the item at the top of this stack.
     *
     * @return the item at the top of this stack
     */

    public Object pop()
    {
	return elements.remove(size() - 1);
    }

    /**
     * Returns the item at the top of this stack.  That item is not
     * removed.
     *
     * @return the item at the top of this stack
     */

    public Object peek()
    {
	return elements.get(size() - 1);
    }

    /**
     * Returns the number of elements on this stack.
     *
     * @return the size of this stack
     */

    public int size()
    {
	return elements.size();
    }

    public void clear()
    {
	elements.clear();
    }

    public String toString()
    {
	return elements.toString();
    }

    public static void main(String[] args)
    {
	Stack s = new Stack();

	System.out.println("Starting pushes");

	for (int i = 0; i < 1000000; i++)
	    s.push(i);

	System.out.println("Finished pushes; starting pops");

	while (s.size() > 0)
	    {
		s.pop();
	    }

	System.out.println("Finished pops");
    }
}
This code can also be downloaded from the files Postfix.java, and Stack.java.