有意思。此题最简单的解法是递归,在纸上画一下就看出来了。
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!head || !head->next) return head;
ListNode* n1 = head;
ListNode* n2 = n1->next;
ListNode* n3 = n2->next;
n2->next = n1;
n1->next = swapPairs(n3);
return n2;
}
};