I am having trouble with this code.
public E remove(int index){ checkInvariants(); if ((index < 0) || index >= size) { String warning = "The index has to be between 0 and " + (size - 1); throw new IndexOutOfBoundsException(warning); } verify (head != null); E val = head.item; if (size == 1) { head = null; tail = head; } else { LinkedNode<E> n = nodeAtPosition(index); val = n.item; if (index == 0) { head = n.next; } n = n.next; } size--; checkInvariants(); return val; // return null; }
my code can compile, however, when I use the above method to remove anything other than the head, an exception is executed, saying that there is an assertion error. I realize that the tail might have something to do with it. If so, how can I correct this method?
Also here is another remove method:
public boolean remove(E element){ LinkedNode<E> temp = head; if(head != null && element.equals(head.item)){ if(head.next != null){ head = head.next; size--; return true; } else{ head = null; size--; return true; } } while(temp.next != null && element.equals(temp.next.item)){ temp = temp.next; size--; return true; } return false; }
This remove method above is supposed to be supporting the LinkedListIterator. However, it isn't. Is there any way to correct this method?