class Solution {
public:
// Recursive
ListNode* swapPairs(ListNode* head) {
// recursion exit condition
if (!head || !head->next) return head;
auto new_head = head->next;
head->next = swapPairs(new_head->next);
new_head->next = head;
return new_head;
}
// Iterative
ListNode* swapPairsII(ListNode* head) {
ListNode dummy{0}, *pre = &dummy;
dummy.next = head;
while (pre->next && pre->next->next) {
ListNode *p = pre->next, *q = p->next;
pre->next = q;
p->next = q->next;
q->next = p;
pre = p;
}
return dummy.next;
}
};