问题描述
我有一个链表,我想根据其中的数据从其中删除一个节点.
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.
如果我删除"temp = temp.previous;"行代码可以工作,但是在我要删除的节点之后删除了该节点.如果我按原样运行它,那么它什么都不会删除.
If I remove the "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.
打印语句显示,我当前正在使用使用findNode(head,a)方法找到的那个节点之前的节点,但是不知何故,只是搞砸了.
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.
推荐答案
如果要删除节点,则需要更改相邻节点的 next
和 previous
字段节点.
If you want to remove a node, you need to alter the next
and previous
fields of neighbouring nodes.
if (temp.next!=null) {
temp.next.previous = temp.previous;
}
if (temp.previous!=null) {
temp.previous.next = temp.next;
}
这将绕过 temp
将 temp
的两个相邻节点彼此链接.
That will link temp
's two neighbouring nodes to each other, bypassing 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.next = null;
temp.previous = null;
如果您对列表的 head
和/或 tail
有单独的引用,则在删除的节点位于开头的情况下,需要重新分配它们或列表的结尾.
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.
这篇关于java删除节点链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!