Why is this removing all elements from my LinkedList?
- by Brian
Why is my remove method removing every element from my Doubly Linked List? If I take out that if/else statements then I can successfully remove middle elements, but elements at the head or tail of the list still remain. However, I added the if/else statements to take care of elements at the head and tail, unfortunately this method now removes every element in my list. What am I do wrong?
public void remove(int n)
{
LinkEntry<E> remove_this = new LinkEntry<E>();
//if nothing comes before remove_this, set the head to equal the element after remove_this
if (remove_this.previous == null)
head = remove_this.next;
//otherwise set the element before remove_this equal to the element after remove_this
else
remove_this.previous.next = remove_this.next;
//if nothing comes after remove_this, set the tail equal to the element before remove_this
if (remove_this.next == null)
tail = remove_this.previous;
//otherwise set the next element's previous pointer to the element before remove_this
else
remove_this.next.previous = remove_this.previous;
//if remove_this is located in the middle of the list, enter this loop until it is
//found, then remove it, closing the gap afterwards.
int i = 0;
for (remove_this = head; remove_this != null; remove_this = remove_this.next)
{
//if i == n, stop and delete 'remove_this' from the list
if (i == n)
{
//set the previous element's next to the element that comes after remove_this
remove_this.previous.next = remove_this.next;
//set the element after remove_this' previous pointer to the element before remove_this
remove_this.next.previous = remove_this.previous;
break;
}
//if i != n, keep iterating through the list
i++;
}
}