[英]remove from double linked list
我是Java,我正在尝试实现从双链表中删除的方法,但我很挣扎,不知道如何推进。 该方法删除存储在列表中给定节点的数据。 我已经读到我需要考虑被删除的元素是开始或结束的情况,但我不知道如何去做。 一般来说,我不确定这是否是正确的方法。 我的代码/进度发布在下面。 如果有任何帮助,将不胜感激。 谢谢
PS我在类中有一个开始和结束参考以及一个大小参考
public type removeAtTheIndex(int index)
{
type theData = null;
Node <type> current= start;
Node temp= new Node();
if (index >= 0 && index < size && start !=null)
{
for (int i=0; i < index && current.getNext()!= null; i++)
{
current=current.getNext();
}
if (current != null)
{
if (current == start)
{
}
else if (current == end)
{
}
else
{
theData= current.getData();
temp= current.getPrev();
temp.setNext(current.getNext());
current.getNext().setPrev(temp);
current.setData(null);
size--;
}
}
return theData;
}
我已将type
更改为Type
。 在 Java 中不推荐使用小写的类名。 我添加了大量评论,希望您能理解发生了什么。
请注意,这不是经过测试的代码。 您可能会在其中发现错误,但我相信流程的本质就在那里。
public Type removeAtTheIndex(int index) {
// I want to return the data that was removed.
Type theData = null;
// Sanity checks.
if (index >= 0 && index < size && start != null) {
// Find the entry with the specified index.
Node<Type> current = start;
for (int i = 0; i < index && (current = current.getNext()) != null; i++) {
}
// Did we find it?
if (current != null) {
// Yes! Gather the contents.
theData = current.getData();
// Clear it.
current.setData(null);
// Special?
if (current == start) {
// Its the start one.
start = start.getNext();
// Detach it.
start.setPrev(null);
} else if (current == end) {
// Step end back one.
end = end.getPrev();
// Detach it.
end.setNext(null);
} else {
// Remove from within list.
Node prev = current.getPrev();
// Point it at my next.
prev.setNext(current.getNext());
// Point my next to new prev.
current.getNext().setPrev(prev);
}
// One less now.
size--;
}
}
return theData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.