title: Swapping Nodes on a single linked list
body: <p>I am trying to make a <code>swapNode</code> function that can take any two nodes and swap them. I've made an algorithm that works if they're at least 2 nodes away, but I can't seem to come up with an algorithm that will work if they are closer to each other.</p>
  
  <p>Here's what I wrote so far:</p>
  
  <pre><code>void swapNode(call * &amp;head, call * &amp;first, call * &amp;second){
      call * firstPrev = NULL;
      call * secPrev = NULL;
      call * current = head;
  
      //set previous for first
      while((current-&gt;next != first) ){
          current = current-&gt;next;
      }
  
      firstPrev = current;
      current = head;
  
      //set previous for second
      while((current-&gt;next != second) ){
          current = current-&gt;next;
      }
  
      secPrev = current;
      current = second-&gt;next;
  
      //set firstPrev-&gt; next to second
      firstPrev-&gt;next = second;
      //set secPrev-&gt;next to first
      secPrev-&gt;next = first;
      //set second-&gt;next = first-&gt;next
      second-&gt;next = first-&gt;next;
      //set first-&gt;next to current
      first-&gt;next = current;
  
      current = head;
      while(current-&gt;next != NULL){
          cout &lt;&lt; current-&gt;number &lt;&lt; endl;
          current = current-&gt;next;
      }
  
      cout &lt;&lt; current-&gt;number &lt;&lt; endl;
  }
  </code></pre>
  
  <p>EDIT:
  I now have this as my swap part, but it still doesn't seem to work correctly</p>
  
  <pre><code>//swap firstPrev-&gt; next with second-&gt;next
  tmp = firstPrev-&gt;next;
  second-&gt;next = firstPrev-&gt;next;
  second-&gt;next = tmp;
  //swap swap first-&gt;next with second-&gt;next
  tmp = first-&gt;next;
  second-&gt;next = first-&gt;next;
  second-&gt;next = tmp;
  </code></pre>
  
  <p>EDIT2:
  This one doesn't seem to work either, I get a seg fault.</p>
  
  <pre><code>    //swap previous's-&gt;next
      tmp =firstPrev-&gt;next;
      secPrev-&gt;next = firstPrev-&gt;next;
      secPrev-&gt;next = tmp;
      //swap swap first-&gt;next with second-&gt;next
      tmp = first-&gt;next;
      second-&gt;next = first-&gt;next;
  second-&gt;next = tmp;
  </code></pre>