[英]Removing the last object in a Node in a manual Linked List implementation (Java)
[英]Java - Manual linked list, removing current node
因此,我从头开始实现了一个链表,并试图删除当前节点(光标)。 当我运行该程序并尝试删除当前节点时,我没有收到任何错误,但是我将尝试打印当前节点(现在应该是下一个或上一个),并且会打印应该的那个节点。已被删除。
首先,这行没有意义:
// ...
}else{
cursor = cursor.getPrev().getNext(); // THIS LINE - all you say here is 'cursor = cursor'
cursor = cursor.getNext();
}
// ...
您可能想断开上一个节点的指向光标的连接,使其指向光标之后的节点:
// get previous node and set its next to node after cursor
cursor.getPrev().setNext(cursor.getNext());
在这一部分:
if(cursor.getNext() == null){ //it's the tail
tail = cursor.getPrev();
}
您永远不会通过说tail.next = null
断开tail.next
的连接,因此您的tail.next
将在更新后指向cursor
。
然后这行:
else{
cursor = cursor.getNext().getPrev(); // again no effect
cursor = cursor.getPrev();
}
应该看起来像:
// get next node and set its prev to node before cursor
cursor.getNext().setPrev(cursor.getPrev());
总体而言,您的逻辑似乎比应该的复杂得多。 这是一种简化代码但不更改逻辑的方法(仍然使用游标节点)
您可以稍微调整一下if
语句的顺序,使事情变得更清楚。 您应该先检查边缘情况(头和尾),然后再检查其余情况:
if (cursor != null){
if(cursor.getPrev() == null){ //it's the head
head = cursor.getNext();
head.setPrev(null); // disconnect the head from current node
} else if (cursor.getNext() == null) { // it's the tail
tail = cursor.getPrev();
tail.setNext(null); // disconnect the tail from current node
} else { // regular node
Node prev = cursor.getPrev();
prev.setNext(next); // connect previous node to next node
Node next = cursor.getNext();
next.setPrev(prev); // connect next node to previous node
}
// this part isn't necessary because we are skipping the cursor node
// so nothing in the list references to it anymore
// however it is a good safety measure and it helps the GC a bit
cursor.setPrev(null); // disconnect cursor from previous node
cursor.setNext(null; // disconnect cursor from next node
}
我省略了游标的更新,因为当游标位于中间节点上并且将其删除时,存在很多情况。 问题是你如何决定更新光标到prev
或next
?
您实际上并不需要光标,但是我已经把这个答案塞满了,所以我会给您this link
和this link
以查看一些好的想法。
至于格式化长印:
如果您使用的是Eclipse,则可以在Windows上使用Ctrl-Shift-F
或在Mac上使用Cmd-Shift-F
来自动设置代码格式:)
我怀疑您打来的电话
cursor = cursor.getPrev().getNext();
(假设光标是您要删除的列表中的元素)没有做任何事情,因为cursor
应该已经 == cursor.getPrev().getNext()
我怀疑你想做的是
cursor.getPrev().setNext(cursor.getNext()); // note SET instead of GET
cursor.getNext().setPrev(cursor.getPrev());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.