Okay so I've created a public E remove(int index) method, it works fine at removing. However, when it removes the node at index size-1, and then I try to add nodes at the end of the list afterwards, it increases the index but DOES NOT add the nodes. I think this is because I didn't made a condition if the index chosen is the tail then to adjust the tail. Here is my method without the tail condition:
public E remove(int index) { Node<E> previous = null; Node<E> current = head; if ( index < 0 || index >= size) throw new IndexOutOfBoundsException(); if (index == 0){ head=head.next; } //remove item somewhere in the middle else { for(int i = 0; i < index; i++) { previous = current; current = current.next; } previous.next = current.next; } size--; return current.data; }
So then I tried to add this condition in if the index chosen is equaled to the tail (size-1).
if(index == size-1) { for(int i=0; i<size-1; i++) { previous=current; current=current.next } previous.next=null; }
But it gives me a null pointer exception! How can I fix this condition so that my code works properly and I am able to add new nodes to the end of the list after deleting and adjusting the tail?