title: Sorting a linked list using selection sort in C++
body: <p>I'm running into some sort of runtime error when trying to test my sort method. With my implementation, I attempt to find the smallest node in a linked list... Following that I test if the smallest node is first node, last node, or just in the middle. After testing for these cases, I then attempt to add the smallest value into a new linked list. I do this into all the values are sorted, then point head(private variable in my class) to the newly sorted list... If I need to include my header file or anything else, please just let me know. Any help is appreciated.</p>
  
  <p>To be clear, there’s no actual error message, the program just gets terminated when I call my sort function. </p>
  
  <pre><code>void Linkedlist::sort()
  {
      Node * current = head;
      Node * smallest = head;
      Node * newHead = NULL;
      Node * newTail = NULL;
  
      while(head != NULL)
      {
          current = head;
          while(current != NULL)
          {
              if(current-&gt;elem &lt; smallest-&gt;elem)
              {
                  smallest = current;
              }
              current = current-&gt;next; 
          }
  
          //smallest is first node
          if(smallest-&gt;prev == NULL)
          {
              head = head-&gt;next;
              head-&gt;prev = NULL;
          }
  
          //smallest is last node
          else if(smallest-&gt;next == NULL)
          {
              tail = tail-&gt;prev;
              tail-&gt;next = NULL;
          }
  
          else
          {
              smallest-&gt;prev-&gt;next = smallest-&gt;next;
              smallest-&gt;next-&gt;prev = smallest-&gt;prev;
          }
  
          //adding smallest to a new linked list
          if(newHead == NULL)
          {
              smallest-&gt;prev = NULL;
              smallest-&gt;next = NULL;
              newHead = smallest;
          }
          else
          {
              smallest-&gt;prev = newTail;
              smallest-&gt;next = NULL;
              newTail-&gt;next = smallest;
              newTail = smallest;
          }
      }
      //point head to new linked list
      head = newHead;
  
  }
  </code></pre>