/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *phead = new ListNode(0);
phead->next = head;
ListNode *prev = phead;
ListNode *curr = head;
while (curr && curr->next) {
ListNode *next = curr->next;
prev->next = next;
curr->next = next->next;
next->next = curr;
prev = curr;
curr = curr->next;
}
return phead->next;
}
};
Small Case: 4ms
Large Case: 16ms
Time: O(n)
Space: O(1)