我做了这个删除最后一个函数,看起来它应该可以工作,但是当我调用它时,它实际上并没有删除任何东西,所有节点仍然在那里。
有什么问题吗?
public Object removeLast()
{
Node currentNode;
currentNode = this.getHead();
while(currentNode != null)
{
if(currentNode.getNext()==null)
{
currentNode = null;
return null;
}
currentNode = currentNode.getNext();
}
return null;
}
最佳答案
您有一个包含节点的列表。每个节点都包含一个指向下一个节点的指针。
要从列表中删除节点,必须将前一个节点的下一个指针设置为空
如果您还有一个指向前一个元素的指针,那么这很简单。像这样的东西:
public Object removeLast()
{
Node currentNode;
currentNode = this.getHead();
while(currentNode != null)
{
if(currentNode.getNext()==null)
{
// The line below is changed!!!
currentNode.getPrevious().setNext(null);
return null;
}
currentNode = currentNode.getNext();
}
return null;
}
如果每个节点都有一个指向下一个和上一个节点的指针,那么我们将其称为双向链表。
<小时/>此外,返回类型不需要是 Object
,您可以将方法签名更改为:
public void removeLast()
然后将每个 return null;
更改为 return;
关于java - 链接列表 - 无法弄清楚为什么此删除最后一个功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20025723/