From 4ae4313646007d73a36d4728aec4c11b559f7439 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 2 Dec 2022 16:15:15 +0800 Subject: [PATCH] s0024 --- src/s0024_swap_nodes_in_pairs.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/s0024_swap_nodes_in_pairs.cpp b/src/s0024_swap_nodes_in_pairs.cpp index e252ca8..34fdbe1 100644 --- a/src/s0024_swap_nodes_in_pairs.cpp +++ b/src/s0024_swap_nodes_in_pairs.cpp @@ -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; }