This commit is contained in:
Sainnhe Park 2022-12-02 16:15:15 +08:00
parent 7bc754ae03
commit 4ae4313646
1 changed files with 10 additions and 4 deletions

View File

@ -1,11 +1,17 @@
#include "s0024_swap_nodes_in_pairs.hpp"
ListNode* S0024::swapPairs(ListNode* head) {
// 只有当 head 和 head->next 都不为空时才翻转
// 其它情况都直接返回
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode *newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
// 从这一行开始就假设 head 和 head->next 都不为空了
// 我们首先把从 head->next->next 开始的链表翻转了
ListNode* ptr = swapPairs(head->next->next);
// 现在我们开始翻转 head 和 head->next
ListNode* ans = head->next;
head->next->next = head;
head->next = ptr;
return ans;
}