Question

Im trying to remove a object from a list using a method with a specific index that I wish to remove. The tricky part here is that this list is a doublelinkedlist and when I remove a node from it, the next and previous pointer needs to be redirected to the correct nodes. Here is what I got so far, but the code does not seem to redirect the pointers correctly, I would appriciate any inputs!

 private static final class Node<T>      
  {
    private T value;
    private Node<T> previous, next;

    private Node(T value, Node<T> previous, Node<T> next) // constructor
    {
      this.value = value;
      this.previous = previous;
      this.next = next;
    }
  }

  private Node<T> head;         // first in the list
  private Node<T> tale;         // last in the list






public T remove(int index)   { 
      indexcontrol(index); // checks if legal index

      Node<T> q, p = null;

      if(index == 0)
      {
          q = head;
          head = head.next;
      }

      else
      {
          p = findNode(index-1); // finds the nodes value on place index
          q = p.next;

          p.next= q.next;
      }

      if ( q== tale) tale = p;

      T value = q.value;
      q.value = null;

      q.next = null;

      return value;

  }
Was it helpful?

Solution

You need to assign the previous and next pointer to the correct node.

public T remove (int index){
    if (index==0){
        //remove head
    }else if (index == size){
        //remove tail
    }
    else {
        Node<T> p = null;
        Node<T> q = null;
        Node<T> r = null;
        p = findNode(index-1); // finds the nodes previous to the node that needs to be removed
        q = p.next; //q is the node you want to remove
        r = q.next; //r is the node next to the node you want to remove

        p.next = r;
        r.previous = p;

        //you can explicitly delete the node, but GC will collect anyway. 
        q.next = null;
        q.previous = null;
        T value = q.value;
        q.value = null;
        return value;
    }
}

OTHER TIPS

You can see the source code of java.util.LinkedList, then you will know how to implement it.

It seems that in else statement you change only one pointer, when you should be changing two of them. Should be something like this:

prevNode.next = origNode.next;
nextNode.prev = origNode.prev;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top