从头开始实现双向链表,remove()方法出错

时间:2016-01-01 13:54:38

标签: java data-structures

我试图学习在java中实现Doubly Linked List,就像练习一样。 但我坚持使用remove()方法。

列表的内容是,

1 2 3 4

当我尝试删除不存在的元素时,会在NullPointerException显示line no. 21而不是打印not found

我看到的其他代码有点复杂,与我正在做的不同。 方法是,

 void remove(int data){
    Node n = head;
    if(head==null)
        System.out.println("Not Found");
    else if(head.d==data){
        if(head==tail){
            head=null;
            tail=null;
        }
        else{
            head=head.next;
            head.prev=null;
        }
    }
    else{
        while(n!=null && n.d==data){
            n=n.next;
        }
        if(n==tail){
            tail=tail.prev;
            tail.next=null;
        }
        else if(n!=null){
            n.prev.next=n.next;
            n.next.prev=n.prev;
        }
        if(n==null)
            System.out.println("Not Found");
    }
}

所以我的问题是, 我完全错了吗? 或者问题是什么? 请原谅我,如果它太愚蠢了。

2 个答案:

答案 0 :(得分:2)

问题在于搜索逻辑。在while循环条件中" n.d == data"是不正确的。它应该是" n.d!= data"即。

while(n!= null&& n.d == data){
            N = n.next;
        }

应该是:

sed -e 's/[^[:alpha:]#][[:alpha:]]*/ /g' \
    -e 's/^[^#]*//' \
    -e 's/  */ /g'

这是一个更清洁的实施:

...

    while(n!=null && n.d != data){
        n=n.next;
    }

答案 1 :(得分:0)

void remove(Node head, int value) {
    if (head == null) {
        System.out.println("Not Found");
    } else if (value == head.d) {
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            head = head.next;
            head.prev = null;
        }
    } else {
        Node n = head.next;
        while (n != null && value != n.d) {
            n = n.next;
        }
        if (n == tail) {
            tail.next = null;
            tail = tail.prev;
        } else if (n != null) {
            n.prev.next = n.next;
            n.next.prev = n.prev;
        }
    }
}