title: Deleting a node in double linked list by an index position
body: <p>I am trying to delete a node from a doubly-linked list, but I get a <code>NullPointerException</code> when I try to delete the 2nd item. I was able to delete the first item and the last item.</p>
  
  <p>Below is my code:</p>
  
  <pre><code>@Override
  public T removeElement(int index) {
      // TODO Auto-generated method stub
      T result = null;
  
      if (IsEmpty()) {
          throw new NoSuchElementException();
      }
  
      if (count == 1 &amp;&amp; index == 0) {
          result = head.getData();
          head = null;
          tail = null;
      }
      if (index == 0) {
          result = head.getData();
          head = head.getNext();
      }
      if (count == index) {
          result = tail.getData();
          tail = tail.getPrev();
          tail.setNext(null);
      }
      int i = 1;
      for (Node&lt;T&gt; current = head; current != null; current = current.getNext()) {
          if (i == index){
              result = current.getData();
              Node&lt;T&gt; previous = current.getPrev();
              Node&lt;T&gt; next = current.getNext();
              previous.setNext(next);
              next.setPrev(previous); //getting null pointer exception here
          }
          i++;
      }
  
      count--;
      return result;
  }
  
  @Override
  public void addElement(T data)//add elements in the list
  {
      Node&lt;T&gt; newNode = new Node&lt;T&gt;(data);
      if (IsEmpty()) {
          head = newNode;
          tail = newNode;
      }
      else {
          newNode.setPrev(tail);
          tail.setNext(newNode);
          tail = newNode;
      }
      count++;
  }
  </code></pre>
  
  <p>Here is my test program:</p>
  
  <pre><code>public class Test {
  
  public static void main(String[] args) {
      DoubleListImpl&lt;Integer&gt; test = new DoubleListImpl&lt;Integer&gt;();
  
      test.addElement(10);
      test.addElement(20);
      test.addElement(40);
      test.addElement(50);
      test.display();
      System.out.println(test.getCount());
      test.removeElement(4);
      System.out.println();
      //test.removeElement(3);
      test.display();
      System.out.println(test.getCount());
  }
  }
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>I noticed something interesting a minute ago. If i made <code>i=0</code> i get a null pointer error when i pass <code>index ==3</code> as an argument in the removeElement function. or when i make i=1 i get a null pointer when i pass <code>i==2</code> as an argument.</p>