Reputation: 9
I'm trying to implement a doubly linked list for a class assignment. I am currently stuck on implementing a method to remove a node at a specified index.
public void remove(int index) {
if (index < 0 || index > count-1) {
throw new ListIndexOutOfBoundsException("The index "+index+" is out of bounds.");
}
if (isEmpty()) {
System.out.println("List is empty");
return;
}
MedicationNode curr = head;
int k = 0;
while(k < index) {
curr = curr.next;
k++;
}
if (curr.prev == null) {
curr.next.prev = null;
}else if(curr.next == null) {
curr = curr.prev;
curr.next = null;
}else{
curr.next.prev = curr.prev;
curr.prev.next = curr.next;
}
count--;
}
the method can remove any specified node in a linked list except index 0. I'm thinking the problem may be with my add method but im not really sure.
Upvotes: 0
Views: 972
Reputation: 11330
In your first if condition -
if (curr.prev == null) {
curr.next.prev = null;
//Make your head of the linked list point to this node
head = curr.next;
}
This is because you are removing the head from the list so the head should point to the head's next node.
Upvotes: 1