[英]Removing a node in a linked list
Trying to remove a node by index now. 现在尝试按索引删除节点。 I'd like to print out the list of nodes with indices so the user can select the index as seen.
我想打印出带有索引的节点列表,以便用户可以选择所看到的索引。 I think my logic is okay in printing the list with the indices but no input is coming out :(
我认为我的逻辑可以打印带有索引的列表,但是没有输入信息:(
At one point in fooling around with this, I was still unable to print the list of nodes but the "enter in the index you wish to delete" was output and was able to take a users' selection but eventually got a NullPointerException. 到此为止,我仍然无法打印节点列表,但是输出了“输入要删除的索引”,并且可以接受用户的选择,但最终得到了NullPointerException。
else if (menu.equals("d")) {
EntryNode temp = head;
while (temp != null) {
for (int i = 0; i < addressBook.length(); i++) {
//gets node at index
System.out.println(temp.getFirstName() + i);
temp = temp.getNext();
}
System.out.println(" ");
System.out.println("Please enter the index of the entry you wish to delete ");
int index = keyboard.nextInt();
addressBook.removeEntry(index);
}
}
The removal method: public void removeEntry(int index){ 删除方法:public void removeEntry(int index){
//delete from the head
if (index == 0) {
EntryNode temp = head;
head = temp.getNext();
temp.setNext(null);
head.setPrev(null);
size--;
}
//delete from the tail
else if (index == length()) {
EntryNode temp = tail;
temp.setPrev(null);
tail.setNext(null);
tail = temp.getPrev();
size--;
}
//in the middle
else {
EntryNode temp = head;
for (int i = 0; i < index; i++) {
//gets node at index
temp = temp.getNext();
}
//set node after temp's previous to temp's previous
temp.getNext().setPrev(temp.getPrev());
temp.getPrev().setNext(temp.getNext());
temp.setNext(null);
temp.setPrev(null);
size--;
}
}
The NullPointerException comes from : NullPointerException来自:
//set node after temp's previous to temp's previous
temp.getNext().setPrev(temp.getPrev());
You should check if temp.getNext()
is not null
before calling the setPrev()
on it. 您应该在调用
setPrev()
之前检查temp.getNext()
是否不为null
。
Also, you should check with length()-1
as you have nodes which are zero indexed. 另外,由于节点索引为零,因此应使用
length()-1
检查。
Indices are in the range [0, length() - 1]
, so you should use 索引的范围是
[0, length() - 1]
,因此您应该使用
else if (index == length() - 1) {
instead. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.