简体   繁体   English

从链表中删除包含键的节点

[英]Remove the node that contains the key from the Linked list

I have a remove method , find the element in that list and delete it.That topic is about Doubly linked list.Is my operation true in if and else if statement for the formation of the new list?我有一个remove方法,找到那个列表中的元素并删除它。那个主题是关于双向链表的。我的操作在if和else if语句中是否正确以形成新列表?

public void Remove(int key) {//key = number in the list.
        if (head == null) {
            System.out.println("Empty List..!");
        } else if (key == head.key) {
            head.prev.next = head.next;
            head.next = null;
            noOfNodes--;
        } else if (key == tail.key) {
            tail.next.prev = tail.prev;
            tail.prev = null;
            noOfNodes--;
        } else {
            for (LinkedListNode temp = head; temp.next != null; temp = temp.next) {
                if (temp.key == key) {
                    temp.prev.next = temp.next;
                    temp.next.prev = temp.prev;
                    temp.prev = null;
                    temp.next = null;
                    noOfNodes--;
                }
            }
        }
    }

From your code, it looks like tail is the last node of your linked list.从您的代码中,看起来tail是链表的最后一个节点。

So, this might be the issue tail.next.prev = tail.prev;所以,这可能是问题tail.next.prev = tail.prev; . . Since tail.next is null as tail is the last element, when you access prev on tail.next it throws NullPointerException .由于tail.nextnull因为tail是最后一个元素,因此当您在tail.next上访问prev ,它会抛出NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM