key: head node & two pointers
Runtime: 4 ms / beats 3.86%
Reference:discuss
/**
* 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 || head->next == NULL)
return head;
ListNode header(0);
header.next = head;
ListNode *a,*b;//,*c;
a = &header; b = head;// c = head->next;
while(b!=NULL && b->next!=NULL)
{
a->next = b->next;
b->next = b->next->next;
a->next->next = b;
a = a->next->next;
b = b->next;
}
return header.next;
}
};