如何解决从双向链表中删除所有小于给定值的节点java
public void deleteSmaller(int data){
System.out.printf("Deleting data smaller than %d",data);
System.out.println("");
dNode current = head;
dNode lastCurrent;
lastCurrent = head.PrevIoUs;
dNode nextCurrent = current.Next;
while(current!= null){
if(data>=current.data){
if(current.PrevIoUs == null){
nextCurrent.setPrevIoUs(null);
}else{
lastCurrent.setNext(nextCurrent);
nextCurrent.setPrevIoUs(lastCurrent);
}
}
current=current.getNext();
lastCurrent=current.PrevIoUs;
nextCurrent=current.Next;
}
}
我想删除所有小于给定数据的节点的数据 但它一直抛出空指针异常。
问题已解决,但我自己尝试更新了它,现在它工作正常。下面的代码工作正常。
public void deleteSmaller(int data){
System.out.printf("Deleting data smaller than %d",data);
System.out.println("");
dNode current = head;
dNode lastCurrent=null,nextCurrent=current.Next ;
while(current.Next!= null){
if(data>=current.data){
if(current.PrevIoUs == null){
nextCurrent.setPrevIoUs(null);
}else{
lastCurrent.setNext(nextCurrent);
nextCurrent.setPrevIoUs(lastCurrent);
}
}
current=current.getNext();
lastCurrent=current.PrevIoUs;
nextCurrent=current.Next;
}
}
解决方法
public void deleteSmaller(int data){
dNode current = head;
dNode lastCurrent;
lastCurrent = head.Previous; // (1)
dNode nextCurrent = current.Next;
while(current!= null){
if(data>=current.data){
if(current.Previous == null){
nextCurrent.setPrevious(null); // (2)
}else{
lastCurrent.setNext(nextCurrent);
nextCurrent.setPrevious(lastCurrent); // (3)
}
}
current=current.getNext();
lastCurrent=current.Previous;
nextCurrent=current.Next;
}
}
(1) 如果您的列表为空,即 head
为空,调用 previous
将导致 NPE。
(2) 如果您的列表只有 1 个节点,即头节点的 nextCurrent
为空,调用 setPrevious
将导致 NPE。
(3) 如果您的 current
节点是最后一个,nextCurrent
将为空,与上述情况相同。
在分配或调用 dNode 的任何方法之前,您应该进行空值检查。
,您正在检查前一个节点是否为空,这很好,因为当前节点可以是头,但是当当前节点是尾(即链表中的最后一个节点)时呢?您还需要检查下一个节点是否为空,还需要检查当前是否是列表中唯一的节点并且需要删除(即下一个和上一个为空)
while(current!= null){
if(data >= current.data){
if (current.Next == null && current.Previous == null)
{
current = null;
break;
}
if(current.Previous == null){
nextCurrent.setPrevious(null);
}else if(current.Next == null){
previousCurrent.setNext(null);
}else{
lastCurrent.setNext(nextCurrent);
nextCurrent.setPrevious(lastCurrent);
}
}
current=current.getNext();
lastCurrent=current.Previous;
nextCurrent=current.Next;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。