Pairwise Swap of nodes without swapping data in LinkedList
<p>I have been trying to do pairwise swap of linkedlist elements. In place of swapping the elements by data, I am swapping them by swapping the links:</p>

<p>input 1: <code>1-&gt;2-&gt;3-&gt;4-&gt;5</code>
output 1: <code>2-&gt;1-&gt;4-&gt;3-&gt;5</code></p>

<p>input 2: <code>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6</code>
output 2: <code>2-&gt;1-&gt;4-&gt;3-&gt;6-&gt;5</code></p>

<pre><code>#include &lt;iostream&gt;
using namespace std;

struct node{
  int data;
  struct node *next;
};

struct node* func(struct node *f, struct node *s){
    if(s==NULL){
        return f;
    }

    struct node *rest1;
    rest1 = s-&gt;next;

    s-&gt;next = f;
    if(rest1){
        f-&gt;next = func(rest1,rest1-&gt;next);
    }

    return s;
}

void show(struct node *head){
    while(head!=NULL){
        cout&lt;&lt;" "&lt;&lt;head-&gt;data;
        head = head-&gt;next;
    }
}

int main() {
    //code
    struct node *head  =(struct node*)malloc(sizeof(struct node));
    head-&gt;data=1;
    head-&gt;next = (struct node*)malloc(sizeof(struct node));

    head-&gt;next-&gt;data = 2;
    head-&gt;next-&gt;next = (struct node*)malloc(sizeof(struct node));

    head-&gt;next-&gt;next-&gt;data = 3;
    head-&gt;next-&gt;next-&gt;next = (struct node*)malloc(sizeof(struct node));

    head-&gt;next-&gt;next-&gt;next-&gt;data = 4;
    //head-&gt;next-&gt;next-&gt;next-&gt;next=(struct node*)malloc(sizeof(struct node));
    //head-&gt;next-&gt;next-&gt;next-&gt;next-&gt;data=5;

    head = func(head,head-&gt;next);
    show(head);
    return 0;
}
</code></pre>

<p>This code works fine for odd length list but does not work for even length.
I think the problem is in:</p>

<pre><code>if(s==NULL){
    return f;
}
</code></pre>

<p>statement which I am using to make previous <code>f-&gt;next=NULL</code> (in case of even length).    </p>