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

For example,

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

not

加一个头结点

/**
* 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) {
if (head == NULL){
return NULL;
}
ListNode dummy(0);
dummy.next = head;
ListNode* p = &dummy;
while (p->next&&p->next->next){
ListNode* next = p->next;
ListNode* next2 = next->next;
ListNode* next3 = next2->next;
p->next = next2;
next2->next = next;
next->next = next3;
p = next;
}
return dummy.next;
}
};