迭代:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode* pre = head, *nex = pre->next;
ListNode* cur = new ListNode(0);
ListNode* hair = cur;
while (pre && nex) {
ListNode* tmp = nex->next;
cur->next = nex;
cur = pre;
pre->next = nex->next;
nex->next = pre;
pre = tmp;
if (pre)
nex = pre->next;
}
return hair->next;
}
};
递归
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode* tmp = head->next->next, *res = head->next;
head->next->next = head;
head->next = swapPairs(tmp);
return res;
}
};