title: Inserting inside a Linked List
body: <p>My <code>insertAfter</code> function in the <code>LinkedList</code> is not working right.</p>
  
  <p>I would really appreciate if someone could point out what's wrong with my code.</p>
  
  <p>Thanks :)</p>
  
  <p>Here is the list struct:</p>
  
  <pre><code>struct ListItem
  {
      T value;
      ListItem&lt;T&gt; *next;
      ListItem&lt;T&gt; *prev;
  
      ListItem(T theVal)
      {
          this-&gt;value = theVal;
          this-&gt;next = NULL;
          this-&gt;prev = NULL;
      }
  };
  </code></pre>
  
  <p>and here is my function to insert inside the list:</p>
  
  <pre><code>template &lt;class T&gt;
  void LinkedList&lt;T&gt;::insertAfter(T toInsert, T afterWhat)
  {
   if(head!=NULL)    
   {
    ListItem&lt;T&gt;*p;
    p=head;
    while(p-&gt;next!=NULL)
    {
     if(p-&gt;value==afterWhat)
     {
      ListItem&lt;T&gt;*k;
      k=new ListItem&lt;T&gt;(toInsert);
      k-&gt;next=p-&gt;next;
      p-&gt;next=k;
      k-&gt;prev=p;
      k-&gt;next-&gt;prev=k;
     }
     else
      p=p-&gt;next;
    }
   }
   else
   {
    head= new ListItem&lt;T&gt;(toInsert);
   }
   //p=NULL;
  }
  </code></pre>