I am trying too delete a node in a doubly linked list, by an index that a user inputs. It seems to make sense for me but after “removing the node” and reprinting the list’s contents, nothing has changed. I’m sure it’s something stupid that I’m missing. Any advice?
public void removeEntryNode() {
System.out
.println("We delete by index here. Type in the number you want to delete");
// print list for selection
temp = head;
while (temp != null && temp.getFirstName() != null) {
System.out.print(temp.getIndex() + " " + temp.getFirstName() + " ");
System.out.print(temp.getLastName() + " ");
System.out.println(" ");
temp = temp.getNext();
}
int selection = keyboard.nextInt();
// Gets node matching index with selection and deletes it
// Next two lines loop through list
while (temp != null && temp.getIndex() != selection) {
temp = temp.getNext();
}
// if it is the head
if (selection == 0) {
head = temp.getNext();
temp.getNext().setPrev(null);
temp.setNext(null);
counter--;
}
// if it is the tail
else if (selection == size()) {
tail = temp.getPrev();
temp.setPrev(null);
temp.setNext(null);
temp.getPrev().setNext(null);
counter--;
} else {
temp.getPrev().setNext(temp.getNext());
temp.getNext().setPrev(temp.getPrev());
temp.setNext(null);
temp.setPrev(null);
counter--;
}
System.out.println("Successfully deleted ");
menu();
}
It’s impossible to pinpoint the exact problem without seeing your entire code.
Nonetheless, I’ll give you some pointers:
1.
It is generally not a good idea for an element in a linked list to keep track of its own index. To keep the indices correct, every insertion or removal would require traversing the list just to update the indices.
2.
There is probably an off-by-one error here.
3.
The last line is guaranteed to throw a
NullPointerException.Once you fix these problems, I recommend stepping through your program in a debugger, to see whether what actually happens is what you expect to happen at each step.