s0024
This commit is contained in:
parent
7bc754ae03
commit
4ae4313646
@ -1,11 +1,17 @@
|
|||||||
#include "s0024_swap_nodes_in_pairs.hpp"
|
#include "s0024_swap_nodes_in_pairs.hpp"
|
||||||
|
|
||||||
ListNode* S0024::swapPairs(ListNode* head) {
|
ListNode* S0024::swapPairs(ListNode* head) {
|
||||||
|
// 只有当 head 和 head->next 都不为空时才翻转
|
||||||
|
// 其它情况都直接返回
|
||||||
if (head == nullptr || head->next == nullptr) {
|
if (head == nullptr || head->next == nullptr) {
|
||||||
return head;
|
return head;
|
||||||
}
|
}
|
||||||
ListNode *newHead = head->next;
|
// 从这一行开始就假设 head 和 head->next 都不为空了
|
||||||
head->next = swapPairs(newHead->next);
|
// 我们首先把从 head->next->next 开始的链表翻转了
|
||||||
newHead->next = head;
|
ListNode* ptr = swapPairs(head->next->next);
|
||||||
return newHead;
|
// 现在我们开始翻转 head 和 head->next
|
||||||
|
ListNode* ans = head->next;
|
||||||
|
head->next->next = head;
|
||||||
|
head->next = ptr;
|
||||||
|
return ans;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user