title: Efficiently swap elements pairwise in a singly linked list
body: <p>I have written a function in C++ that works fine to swap elements pairwise in a singly linked list. However, I was wondering if there was more efficient way to do the same. To be specific the function I wrote has a case which deals when there are only two elements in the linked list. I was wondering if this case can be omitted and put in the general case. I tried doing that but failed to get the output. Is it possible? Here is my code snippet...</p>
  
  <pre><code>struct Node* swap(struct Node* head){
    struct Node* temp = NULL;
    struct Node* cur;
    struct Node* next;
  
    cur = head;
    next = cur-&gt;next;
  
    // Empty list.
    if(head == NULL){
      cout&lt;&lt;"List is empty. \n";
      return NULL;
    }
  
    // Only one element in the list.
    if(next == NULL){
      return cur;
    }
  
    // If two elements in the list.
    else if(next-&gt;next == NULL){
      cur-&gt;next = NULL;
      next-&gt;next = cur;
      return next;
    }
  
    // General case.
    else{
      head = next;
      while(cur!=NULL){
  
        if(next == NULL)
          break;
  
        if(next-&gt;next == NULL)
          break;      
  
        cur-&gt;next = next-&gt;next;
        next-&gt;next = cur;
  
  
        if(temp == NULL)
          temp = cur;
  
        else{
          temp-&gt;next = next;
          temp = cur;
         }    
  
         cur = cur-&gt;next;
         next = cur-&gt;next;
  
  
       }
      return head;
      }
   }
  </code></pre>