title: Swap adjacent element in a linked list
body: <p>While seeing a programming interview site, I came across code which swap adjacent elements in a linked list, but I found it to be a bit wrong. Below is the code.</p>
  
  <pre><code>void swap (struct list **list1)
  {
      struct list *cur, *tmp, *next;
      cur = *list1;
      if (cur &amp;&amp; cur-&gt;next)
          *list1 = cur-&gt;next;
  
      //To make sure that we have at least two more elements to be swapped.
      while (cur &amp;&amp; cur-&gt;next)
      {
          next = cur-&gt;next;
          tmp = next-&gt;next;
          next-&gt;next = cur;
          //We have to make 1-&gt;next as 4 in above example (figure).
  
          if (tmp)
              cur-&gt;next = tmp-&gt;next;
          cur = tmp;
      }
      return;
  }
  </code></pre>
  
  <p>Now for me, the condition <code>if (temp)</code> is not right here. Is that assessment correct?</p>
  
  <p>Suppose we do have a linked list like:</p>
  
  <pre><code>  1-&gt;2-&gt;3-&gt;4-&gt;NULL
  </code></pre>
  
  <p>Now our objective is to make a linked list like:</p>
  
  <pre><code>2-&gt;1-&gt;4-&gt;3-&gt;NULL
  </code></pre>
  
  <p>My worry is if the <code>if (temp)</code> is there in our code, we can't assign null at end of the linked list.</p>