Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You maynotmodify the values in the list's nodes, only nodes itself may be changed.

 

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {



ListNode *head_1=(ListNode*)malloc(sizeof(ListNode));
head_1->next=head;


ListNode *p=head_1;
ListNode *r=p->next;
if(r==NULL) return head_1->next;
ListNode *q=r->next;
if(q==NULL) return head_1->next;
while(p)
{


p->next=q;

r->next=q->next;

q->next=r;
p=r->next;

p=r;
if(p->next==NULL) break;
r=p->next;
q=r->next;
if(q==NULL) break;
}




return head_1->next;


}
};