简体   繁体   English

java删除节点链接列表

[英]java remove node linked list

I have a linked list and I want to remove a node from it based on the data inside of it. 我有一个链表,我想根据其中的数据从其中删除一个节点。

public Node deleteNode(String a){

    Node<String> temp = findNode(head, a);

    temp = temp.previous;

    System.out.println(temp.data);

    temp = temp.getNext().getNext();

    return temp;

}

This is the code I have for it, which in theory should work but it's doing nothing. 这就是我的代码,理论上应该可以,但是什么也没做。

If I remove the "temp = temp.previous;" 如果我删除“ temp = temp.previous;” line the code works but removes the node after the one I want removed. 行代码有效,但是在我要删除的节点之后删除了该节点。 If I run it as is then it just doesn't remove anything. 如果我按原样运行,那么它什么都不会删除。

The print statement shows that I'm currently working with the node previous to the one found using the findNode(head, a) method but somehow something just gets screwed up. 打印语句表明,我当前正在使用使用findNode(head,a)方法找到的那个节点之前的节点,但是某种程度上它只是搞砸了。

If you want to remove a node, you need to alter the next and previous fields of neighbouring nodes. 如果要删除节点,则需要更改相邻节点的nextprevious字段。

if (temp.next!=null) {
    temp.next.previous = temp.previous;
}
if (temp.previous!=null) {
    temp.previous.next = temp.next;
}

That will link temp 's two neighbouring nodes to each other, bypassing temp . 这将使temp的两个相邻节点彼此链接,从而绕开temp

Then it would probably make sense to remove temp 's references to its neighbours so it doesn't look like it is still part of the list. 然后删除temp对其邻居的引用可能很有意义,因此看起来它仍然不是列表的一部分。

temp.next = null;
temp.previous = null;

If you have separate references to the head and/or tail of your list, you need to reassign them in the case where the node you removed lay at the beginning or end of the list. 如果你有单独的引用head和/或tail列表中,你需要重新分配他们在该节点您删除在列表的开头或结尾外行的情况。

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

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