将字符串推送到堆栈<e> </e>

时间:2013-11-20 22:49:04

标签: java linked-list stack

我正在编写一个程序,使用堆栈和LinkedList将中缀转换为postfix。我需要将“(”插入堆栈,但方法push()接受E项。据我所知,实际上没有办法转换String,例如{ {1}}输入"(",所以我可以推送它。我在尝试推送字符串时得到E。如果有人可以善待审核我的代码并且可能会给我一个提示正确的方向,我真的很感激!!

NullPointerException

LinkedList.java:

Stack myStack = new Stack();

list.push("(");


public void push(E item)
    {
        //private LinkedList<E> list;(This is initiated in another class.)
        list.insertAtFront(item);

    }

public void insertAtFront(E insertItem)
    {
        if(isEmpty())
        {
            firstNode = lastNode = new ListNode< E >(insertItem);
            numElements++;
        }
        else
        {
            firstNode = new ListNode< E >(insertItem, firstNode);
            numElements++;
        }
    }

Postfix.java:     import java.util.Scanner;

public class LinkedList< E >
{
    private ListNode< E > firstNode;
    private ListNode< E > lastNode;
    private int numElements;
    private String name;

    public LinkedList()
    {
        firstNode = null;
        lastNode = null;
        numElements = 0;
    }

    public LinkedList(String listName) 
    {
        name = listName;
        firstNode = null;
        lastNode = null;
        numElements = 0;
    }

    // Method Name      : insertAtFront
    // Parameters       : E insertItem
    // Return value(s)  : Void.
    // Partners         : None.
    // Description      : Inserts a new element at the front of a list
    public void insertAtFront(E insertItem)
    {
        if(isEmpty())
        {
            firstNode = lastNode = new ListNode< E >(insertItem);
            numElements++;
        }
        else
        {
            firstNode = new ListNode< E >(insertItem, firstNode);
            numElements++;
        }
    }

    // Method Name      : insertAtBack
    // Parameters       : E insertItem
    // Return value(s)  : Void.
    // Partners         : None.
    // Description      : Inserts a new element at the back of a list
    public void insertAtBack(E insertItem)
    {
        if(isEmpty())
        {
            firstNode = lastNode = new ListNode< E >(insertItem);
            numElements++;
        }
        else
        {
            lastNode = lastNode.nextNode = new ListNode< E >(insertItem);
            numElements++;
        }
    }

    // Method Name      : removeFromFront
    // Parameters       : 
    // Return value(s)  : 
    // Partners         : None.
    // Description      : 
    public E removeFromFront() throws EmptyListException
    {
        if(isEmpty())
        {
            throw new EmptyListException(name);
        }

        E removedItem = firstNode.data;

        if(firstNode == lastNode)
        {
            firstNode = lastNode = null;
            numElements--;
        }
        else
        {
            firstNode = firstNode.nextNode;
            numElements--;
        }

        return removedItem;
    }

    // Method Name      : removeFromBack
    // Parameters       : None.
    // Return value(s)  : E removedItem
    // Partners         : None.
    // Description      : Removes and Returns the last element.
    public E removeFromBack() throws EmptyListException
    {
        if(isEmpty())
        {
            throw new EmptyListException(name);
        }

        E removedItem = lastNode.data;

        if(firstNode==lastNode)
        {
            firstNode = lastNode = null;
            numElements--;
        }
        else
        {
            ListNode< E > current = firstNode;

            while(current.nextNode != lastNode)
            {
                current = current.nextNode;
            }

            lastNode = current;
            current.nextNode = null;
            numElements--;
        }

        return removedItem;
    }

    // Method Name      : remove
    // Parameters       : int index
    // Return value(s)  : Void.
    // Partners         : None.
    // Description      : Removes the element at the specified index.
    public void remove(int index) throws EmptyListException, IndexOutOfBoundsException
    {
        if(isEmpty())
        {
            throw new EmptyListException(name);
        }

        if(index<0 || index>numElements)
        {
            throw new IndexOutOfBoundsException(name);
        }

        ListNode<E> current = firstNode;

        for(int i = 0;i<index;i++)
        {
            current = current.nextNode;
        }
        while(current.nextNode != lastNode)
        {
            current.data = current.nextNode.data;
            current = current.nextNode;
        }
        lastNode = null;
        numElements--;
    }

    // Method Name      : get
    // Parameters       : int index
    // Return value(s)  : E current.data
    // Partners         : None.
    // Description      : Returns the value of the element at the specified index.
    public E get(int index) throws EmptyListException, IndexOutOfBoundsException
    {
        if(isEmpty())
        {
            throw new EmptyListException(name);
        }

        if(index<0 || index>numElements)
        {
            throw new IndexOutOfBoundsException(name);
        }

        ListNode<E> current = firstNode;

        for(int i = 0;i<index;i++)
        {
            current = current.nextNode;
        }

        return current.data;
    }

    // Method Name      : findAndRemove
    // Parameters       : E item
    // Return value(s)  : boolean
    // Partners         : None.
    // Description      : Searches for the specified element. Returns true it removed, false if not.
    public boolean findAndRemove(E item) throws EmptyListException
    {


        if(isEmpty())
        {
            throw new EmptyListException(name);
        }

        ListNode< E > current = firstNode;

        while(current.nextNode != lastNode)
        {
            if(current.data != item)
            {
                current = current.nextNode;
            }
            if(current.data == item)
            {
                while(current.nextNode != lastNode)
                {
                    current.data = current.nextNode.data;
                    current = current.nextNode;
                }
                current.data = current.nextNode.data;
                current.nextNode.data = null;
                lastNode = null;
                numElements--;
                return true;
            }

            if(current.data == null)
            {
                break;
            }
        }
        return false;
    }

    // Method Name      : findItem
    // Parameters       : E item
    // Return value(s)  : int index
    // Partners         : None.
    // Description      : Returns the index where the specified element it located.
    public int findItem(E item)
    {
        int index = 0;
        ListNode< E > current = firstNode;

        if(isEmpty())
        {
            throw new EmptyListException(name);
        }

        while(current.nextNode != lastNode)
        {
            if(current.data == item)
            {
                return index;
            }
            /*else if(current.data == null)
            {
                current = current.nextNode;
            }*/
            else
            {
                current = current.nextNode;
                index++;
            }
        }

        return -1;
    }

    // Method Name      : lengthIs
    // Parameters       : None.
    // Return value(s)  : int numElements
    // Partners         : None.
    // Description      : Returns the number of elements in the list
    public int lengthIs()
    {
        return numElements;
    }

    // Method Name      : clear
    // Parameters       : None.
    // Return value(s)  : Void.
    // Partners         : None.
    // Description      : Clears all elements from the list
    public void clear()
    {
        numElements = 0;
        firstNode = null;
        lastNode = null;
    }

    // Method Name      : print
    // Parameters       : None.
    // Return value(s)  : Void.
    // Partners         : None.
    // Description      : Prints each element of the list.
    public void print()
    {
        ListNode< E > current = firstNode;

        if(firstNode == null && lastNode == null)
        {
            System.out.println("Empty Integer List");
        }

        else
        {
            System.out.print("The list " + name + " is: ");
            while(current.nextNode != lastNode)
            {
                if(current.data != null)
                {
                    System.out.print(current.data + " ");
                    current = current.nextNode;
                }
                else
                {
                    current = current.nextNode;

                }


            }

            if(current.data != null)
            {
                System.out.print(current.data + " ");
                current = current.nextNode;
                if(current.data != null)
                {
                    System.out.print(current.data + " ");
                    System.out.println();
                }
            }
            else
            {
                System.out.println();
            }

        }
    }

    // Method Name      : isEmpty
    // Parameters       : None.
    // Return value(s)  : boolean
    // Partners         : None.
    // Description      : Returns true if the list is empty, false if not.
    public boolean isEmpty()
    {
        if(numElements==0)
            return true;
        else
            return false;
    }

}

Stack.java

    public class Postfix extends Stack<Object>
{
    final static int PRECEDENCE_PLUS=  1;
    final static int PRECEDENCE_MINUS=  1;
    final static int PRECEDENCE_MULTIPLIY=  2;
    final static int PRECEDENCE_DIVIDE=  2;
    final static int PRECEDENCE_EXPONENT=  3;
    final static int PRECEDENCE_PARANTHESIS=  4;

    //Push left parenthesis '(' onto the stack
        //Append a right parenthsis ')' to the end of infix
        //While the stack is not empty, read infix from left to right and do the following:
            //If the current character in ifx is a digit, append it to postfix
            //If the current character infix is a left parenthesis, push it onto the stack
            //If the current character in infix is an operator:
                //Pop operators (if there are any) at the top of the stack while they have equals or higher precedence than the current operator, and append the popped operators to postfix.
                //Push the current character in infix onto the stack.
            //If the current character in infix is a right parenthesis:
                //Pop operators from the top of the stack and append them to postfix until a left parenthesis is at the top of the stack.
                //Pop and discard the left parenthsis from the stack

    public static boolean isOperator(char op)
    {
        switch(op)
        {
            case '+': return true;
            case '-': return true;
            case '*': return true;
            case '/': return true;
            case '%': return true;
            default: return false;
        }
    }

    public static StringBuffer infixToPostfix(StringBuffer infix) throws InvalidCharacterException
    {
        StringBuffer postfix = new StringBuffer("");

        infix.append(')');
        Stack<String> myStack = new Stack<String>();
        myStack.push("(");
        int i = 0;
        while(infix.length()>0)
        {
            if(Character.isDigit(infix.charAt(i)))
            {
                postfix.append(infix.charAt(i));
                infix.delete(i,i+1);
            }
            if(infix.charAt(i) == '(')
            {
                myStack.push("(");
            }
            if(isOperator(infix.charAt(i)) == true)
            {
                Object E = myStack.peek();
                char peekedItem = E.toString().charAt(0);
                if(isOperator(peekedItem) == true)
                {
                    myStack.pop();
                    infix.delete(i,i+1);
                }
            }
            i++;
        }


        return postfix;
    }

    public static double evaluatePost(StringBuffer postfix)
    {
        return 0;

    }

    public static void main(String[] args) throws InvalidCharacterException, NullPointerException
    {
        Scanner in = new Scanner(System.in);
        String input;
        StringBuffer infix;

        System.out.print("Enter infix expression: ");
        input = in.nextLine();
        infix = new StringBuffer(input);
        try
        {
        System.out.print("Postfix: " + infixToPostfix(infix));
        }
        catch (InvalidCharacterException E)
        {
            System.out.println(E);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Stack类中,您声明了一个实例变量list,但您从未初始化它,因此Java将其初始化为null

初始化:

private LinkedList<E> list = new LinkedList<E>();