java - 线程中出现异常 "main"java.lang.NullPointerException 错误 - Eclipse Java 链表

标签 java eclipse nullpointerexception linked-list stack

我正在创建一个堆栈数据结构并使用链接列表来实现它。我正在使用 3 个 java 文件 - stack.java、stacktest.java 和 linkedList.java。当我测试它时,链接列表工作正常,但堆栈测试给了我以下错误

Is Empty?: true
Is Empty?: false
Exception in thread "main" java.lang.NullPointerException
    at Stack.Peek(Stack.java:56)
    at StackTest.main(StackTest.java:12)

这是我的 stack.java 文件

 import java.util.EmptyStackException;

public class Stack{

    linkedList list;
    int count;

    public Stack()
    {
        list = new linkedList();
        count = 0;
    }

    /**
     * Adds a node to the head of the list
     * @param c character to add
     */
    public void Push(char c)
    {
        if(list.isEmpty())
        {// If the list is empty
            list.addFirst(c); // Add first
            count++;
        }
        else
        {
            list.addAtEnd(c); // To the end (tail acts as head)
            count++;
        }
    }

    /**
     * Removes a node from the head of the list
     * @return char removed node
     */
    public char Pop() throws EmptyStackException 
    {
        if (!isEmpty())
        {
            return list.removeLast();
        }
        else
        {
            throw new EmptyStackException();
        }
    }

    /** 
     * Returns the char from the head of the list
     * @return char from top of the list
     */
    public char Peek() throws EmptyStackException 
    {
        if (!isEmpty())
        {
            return list.getTail().ch;
        }
        else
        {
            throw new EmptyStackException();
        }
    }

    /**
     * Is the list empty?
     * @return true=yes false=no
     */
    public boolean isEmpty()
    {
        return list.isEmpty();
    }

    /**
     * Counts number of nodes within the list
     * @return int # nodes in list
     */
    public int getCount()
    {
        int counter = 0;
        Node temp = list.getHead(); // Get head pointer.
        while(temp.next != null) // Iterate until tail is reached.
            counter++; // Increment counter on each node
        return counter;
    }

    public void printStack()
    {
        list.printList();
    }
}

我的stacktest.java

   import java.io.IOException;

public class StackTest {

    public static void main(String args[]) throws IOException
    {
    Stack stackList = new Stack();
    System.out.println("Is Empty?: " + stackList.isEmpty());
    stackList.Push('A');
    System.out.println("Is Empty?: " + stackList.isEmpty());
    stackList.Pop();
    stackList.Peek();
    stackList.isEmpty();
    stackList.getCount();
    stackList.printStack();

    }

}

还有我的 linkedList.java

    class Node
{
    protected char ch;
    protected Node next;
    protected Node previous;

    /**
   * Construct a node with the given character value 
   * @param c - The character 
    */
    public Node (char c)
    {
        this.ch = c;
        this.next = null;
        this.previous = null;
    }
}   

public class linkedList
{  /** A reference to the head of the list */
    protected Node head;
    protected Node tail;
    /**
   * Construct a new empty list 
    */
    public linkedList()
    {
        head=null;
        tail=null;
    }

    public Node getHead()
    {
        return head;
    }

    public Node getTail()
    {
        return tail;
    }

/**
 *Set c as first node in the list
 *@param c The character to be inserted
 */
    public void addFirst(char c)
    {
        Node newNode = new Node(c);
        head=newNode; // Adding new element.
        tail=newNode; // Head and tail will be the same.
    }

    /**
 *Add a character to the end of the list 
 *@param c The character to be inserted
 */
    public void addAtEnd(char c)
    {
        Node nod = new Node(c);
        Node temp = head;
        while (temp.next != null) // cycle until at end of list.
            temp = temp.next;
        temp.next=nod; // last element is new node.
        nod.previous=temp; // linking last node with rest of list.
        tail=nod; // new node is the tail.
    }

    /**
     *Add a character in alphabetical order into the list 
     *@param c The character to be inserted
    */
    public void addInOrder(char c)
    {

        Node n= new Node(c);

        if(isEmpty())
        {
            addFirst(c);
        }
        else
        {
        Node pre=head;
        Node succ= head.next;
        if (n.ch < pre.ch)
            {
                n.next =head;// join node n to the list at the head.
                head = n;// head is reading from n.
            }
        else
        {

        while(succ!=null && n.ch > succ.ch)
        {   // find the position to insert the node
            pre = succ;
            succ = pre.next;

        }   //rearrange pointers    
       n.next = succ;
       pre.next = n;
        }
        }
    }
    /**
     *Test to see if this list is empty 
     *@returns true or false
    */  
    public boolean isEmpty()
    {
        return (head == null && tail == null);
    }


    /**
     *removes a node from the head of the list 
     *@returns c The character from the removed node
    */
    public char removeFirst() 
    {
        if(!isEmpty())
        {
    // a temporary pointer to enable return of the char being removed
            Node temp = head;
            head = head.next;   //  move head pointer along the list
            return temp.ch;
        }
        else 
        {
            System.out.println("List is empty");
            return '?'; //to indicate that the list is empty
        }
    }

    /**
     * removes a node from the tail of the list 
     * @return c The character from the removed node
     */
    public char removeLast()
    {
        Node t = getTail(); // Retrieve tail
        tail = t.previous; // Set tail to previous node
        return t.ch; // return character
    }

    /**
     *prints the characters in the list
    */
    public void printList()
    {
        Node temp=head;
        while(temp!=tail.next)
        {
            System.out.print(temp.ch + " ");
            temp=temp.next;
        }
        System.out.println(); // After print, goes to new line.
    }

}

我知道我使用的变量为空,但有人可以向我解释一下我哪里出错了

最佳答案

当您调用addFirst()时,它会将头和尾都设置为新节点。但是,当您 removeLast() 时,它只会将 tail 更改为 null 并将 head 设置为您弹出的节点。

然后,当您调用 isEmpty() 时,由于 head 不是 null,因此它无法识别列表为空并返回 false。

您需要修改removeLast()来检查是否删除列表中的唯一元素,并相应地更新头部。

关于java - 线程中出现异常 "main"java.lang.NullPointerException 错误 - Eclipse Java 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176580/

相关文章:

java - "The type javax.el.ValueExpression cannot be resolved"扩展checkbox相关jsf组件时出错

java - 将许多 JBoss 实例的日志输出存储在单个位置

java - Eclipse JSP "cannot be resolved to a type"Apache 公共(public)资源

java - 线程空指针异常

java - 不幸的是(android应用程序)已经停止了。空指针异常

java - BroadcastReceiver 仅触发一次

java - 为什么 FindBugs 在显式抛出 NPE 时会发出严重警告?

php - Xdebug 已安装,但未显示在 Xampp 的 Phpinfo 中

eclipse - Ext-Js 4 开发工具

java - Android:NullPointerException,这里什么可能为空?