java - 使用LLList的代码中的错误

标签 java error-handling linked-list

我正在尝试编写代码,以从列表中删除所有一项,但是当我尝试使用表示空指针异常的方法时遇到错误。
哪一行导致此错误,我该如何解决?删除项目后,它还应该返回true;如果没有出现,则返回false。

更新:错误是该行对象item2 = trav.item

public boolean removeAll(Object item){
    Node trav = head;
    while(trav != null){
        Object item2 = trav.item;
        // it could be `item2.equals` 
        if(item2.equals(item)){
            trav.next = trav;
            return true;
        }
        trav = trav.next; 
    }  
    return false;
}

最佳答案

除了我修复您的NPE。

如果您在修复删除代码时遇到问题,请查看此作为引用,它已经过测试。

我加入评论以解释正在发生的事情。

public class LList {

    // very basic singly linked node
    class Node {
        public Node next;
        public Object item;
        public Node(Object o) {
            item = o;
        }
    }

    // the head and tail of this list
    Node head = null;
    Node tail = null;

    public boolean removeAll(Object item) {
        int count = 0;
        if (head == null)
            return false;

        // while `head.item.equals(item)` remove the head
        while (head != null && item.equals(head.item)) {
            head = head.next;
            count++;
        }
        // don't need to worry about updating `head` anymore
        // because now `!head.item.equals(item)`, else `head == null`
        if (head == null)
            return count > 0;

        // previous and current nodes
        Node prev = head; // !head.item.equals(item)
        Node curr = head.next;
        while (curr != null) {
            if (item.equals(curr.item)) {
                // to remove `curr` make the previous node skip it
                // and link to the next node instead
                prev.next = curr.next;
                count++;
            } else {
                // if curr was removed then prev stays put
                // otherwise curr is the new prev
                prev = curr;
            }
            // always move curr forward
            curr = curr.next;
        }
        return count > 0;
    }

关于java - 使用LLList的代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673702/

相关文章:

java - 使用 SimpleDateFormat 将字符串转换为日期会返回随机日期

java - 如何覆盖依赖jar的spring上下文占位符?

node.js - Node Express RESTful API默认引擎用于错误处理

python - Python修改链表节点 "in place"

java - 正则表达式引擎在没有另一次传递的情况下无法匹配所有出现的情况

java - HashMap 作为字符串的 ArrayList

python - 缺少 com.apple.xbs 文件夹,如何获取它?

vba - 引用另一张纸时出现“Subscript out of range”错误

将元素添加到整数排序列表时的困惑

c++ - 调试后缀计算器