递归解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode *next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return next;
}
};
迭代解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *temp = dummy;
while (temp->next != nullptr && temp->next->next != nullptr) {
ListNode *start = temp->next;
ListNode *end = temp->next->next;
temp->next = end;
start->next = end->next;
end->next = start;
temp = start;
}
return dummy->next;
}
};