title: C++ delete element function in a doubly linked list
body: <p>I'm fairly new to C++ and it's data structures. I've made a few functions for my Doubly Linked List Class but i'm having trouble in the delete functions specifically. I've made a deleteHead() function which delete's the first node in the list, a deleteTail() function which deletes the last node in the list and finally a deleteElement(Item) function which goes over the list and deletes the node which has that the Item in it. </p>
  
  <p>Problem is that whenever I try to delete the only remaining node from the list, the program crashes. i.e If I insert a node and then I call the deleteElement function on the same node (and if the node I inserted is the only node in the list) the program crashes.</p>
  
  <p>here's my code.</p>
  
  <pre><code>template &lt;class T&gt;
  void LinkedList&lt;T&gt;::deleteElement(T item)
  {
      ListItem&lt;T&gt;* current = head;
      ListItem&lt;T&gt;* temp;
      if (head == NULL) {                         // if list is empty end the function
          return;
      }
      while (current) {
          if (current-&gt;value == item) {
              if (current == head) {              // if item is in the head
                  deleteHead();
              }
              else if (current == getTail()) {    // if item is in the tail
                  deleteTail();
              }
              // if item is between two nodes
              else if (current != head &amp;&amp; current != getTail()) { 
                  temp = current;
                  temp-&gt;prev-&gt;next = temp-&gt;next;
                  temp-&gt;next-&gt;prev = temp-&gt;prev;
                  current-&gt;next = NULL;
                  current-&gt;prev = NULL;
                  if (current-&gt;next == NULL) {
                      deleteTail();
                  }
              }
          }
          current = current-&gt;next;
      }
  }
  
  // Delete the Head Node
  template &lt;class T&gt;
  void LinkedList&lt;T&gt;::deleteHead()
  {
      if (head != NULL) { // as long as head is not null, delete head
          ListItem&lt;T&gt; *current = head;
          head = head-&gt;next;
          current-&gt;next = NULL;
          head-&gt;prev = NULL;
      } else {return;} // if head is null, end the function without doing anything
  }
  
  // Delete Tail Node
  template &lt;class T&gt;
  void LinkedList&lt;T&gt;::deleteTail()
  {
      ListItem&lt;T&gt; *tail = getTail();
      tail = tail-&gt;prev;
      tail-&gt;next-&gt;prev = NULL;
      tail-&gt;next = NULL;
  }
  </code></pre>