我试图根据Java中的给定字符串参数从双链表中删除节点,但问题是当从索引1+中删除节点时,除了删除索引0节点外,没有Null错误,我总是得到Null错误。为什么?(这个链表的头是(null, null, Node1)
public boolean remove(String item){
boolean isFound = false;
if(header.next == null)
return false;
Node temp = header;
while(temp.next != null) {
temp = temp.next;
if(temp.value.equals(item)) {
isFound = true;
break;
}
}
if(temp == null || isFound == false)
return false;
Node p = temp.previous;
Node n = temp.next;
p.next = n;
if(n != null) {
n.previous = p;
}
temp = null;
return true;
}
public void addLast(String item){
Node n = new Node();
n.value = item;
if(header.next == null) {
header.next = n;
}
else {
Node temp = header;
while(temp.next != null)
temp = temp.next;
temp.next = n;
n.previous = temp;
temp = header;
}
}
class Node {
String value;
Node next;
Node previous;
public String toString() {
return value == null ? "null" : value;
}
}
public static void main(String[] args){
DoublyLinkedList list = new DoublyLinkedList();
list.addLast("Bob");
list.addLast("Steve");
list.addLast("Harry");
list.remove("Bob");
System.out.println(list);
}
我假设header
代表链表中的第一项。我相信这是因为你没有检查header本身是否已经是我们想要删除的项目。在addLast()中,您也没有考虑如果header为空(当列表中没有项目时)
public class DoublyLinkedList {
public Node header;
public boolean remove(String item){
if (header == null) // add this code
return false;
if (header.value.equals(item)) { // add this code
header = header.next;
header.previous = null;
return true;
}
boolean isFound = false;
if(header.next == null)
return false;
Node temp = header;
while(temp.next != null) {
temp = temp.next;
if(temp.value.equals(item)) {
isFound = true;
break;
}
}
if(temp == null || isFound == false)
return false;
Node p = temp.previous;
Node n = temp.next;
p.next = n;
if(n != null) {
n.previous = p;
}
temp = null;
return true;
}
public void addLast(String item){
Node n = new Node();
n.value = item;
if (header == null) { // add this code
header = n;
}
else if(header.next == null) {
header.next = n;
}
else {
Node temp = header;
while(temp.next != null)
temp = temp.next;
temp.next = n;
n.previous = temp;
temp = header;
}
}
class Node {
String value;
Node next;
Node previous;
public String toString() {
return value == null ? "null" : value;
}
}
public void showAll() {
if (header == null) return;
Node temp = header;
while (temp.next != null) {
System.out.println(temp);
temp = temp.next;
}
System.out.println(temp);
}
public static void main(String[] args){
DoublyLinkedList list = new DoublyLinkedList();
list.addLast("Bob");
list.addLast("Steve");
list.addLast("Harry");
list.remove("Bob");
list.showAll();
}
}