gpt4 book ai didi

java - 从零开始实现双向链表,remove()方法出错

转载 作者:搜寻专家 更新时间:2023-11-01 03:19:36 26 4
gpt4 key购买 nike

我试图学习在 java 中实现双向链表只是作为练习。但我被困在 remove() 方法中。

列表的内容是,

1 2 3 4

当我尝试删除不存在的元素时。它在 行号处显示 NullPointerException。 21 而不是打印 not found

我看到的其他代码有点复杂,与我正在做的不同。方法是,

 void remove(int data){
Node n = head;
if(head==null)
System.out.println("Not Found");
else if(head.d==data){
if(head==tail){
head=null;
tail=null;
}
else{
head=head.next;
head.prev=null;
}
}
else{
while(n!=null && n.d==data){
n=n.next;
}
if(n==tail){
tail=tail.prev;
tail.next=null;
}
else if(n!=null){
n.prev.next=n.next;
n.next.prev=n.prev;
}
if(n==null)
System.out.println("Not Found");
}
}

所以我的问题是,我做的完全错了吗?或者有什么问题?如果这太愚蠢了,请原谅我。

最佳答案

问题出在搜索逻辑上。在 while 循环条件中“n.d == data”是不正确的。它应该是“n.d != data”即

while(n!=null && n.d==data){
n=n.下一个;

应该是:

...

while(n!=null && n.d != data){
n=n.next;
}

这是一个更简洁的实现:

public void remove(int data) { // Head is not required in param, should be field variable
Node ptr = head;

while(ptr!=null && ptr.data != data) // search for the node
{
ptr = ptr.next;
}

if(ptr == null) {
System.out.println("Not Found");
return;
}

if(ptr.prev == null) {// match found with first node
head = ptr.next;
}
else{
ptr.prev.next = ptr.next;
}
if(ptr.next == null){// match found with last node
tail = ptr.prev;
}
else{
ptr.next.prev = ptr.prev;
}
}

关于java - 从零开始实现双向链表,remove()方法出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com