#include "s0206_reverse_linked_list.hpp" // 双指针法 ListNode* S0206::reverseList1(ListNode* head) { if (head == nullptr) { return nullptr; } ListNode* pre = head; ListNode* cur = head->next; pre->next = nullptr; ListNode* curNext; while (cur != nullptr) { curNext = cur->next; cur->next = pre; pre = cur; cur = curNext; } return pre; } // 递归法 ListNode* S0206::reverseList2(ListNode* head) { if (head == nullptr) { return nullptr; } else if (head->next == nullptr) { return head; } // 翻转从第二个节点开始的链表 // 翻转完后 head->next 指向这个链表的末尾,而这个链表的末尾元素的 next // 指向空指针 ListNode* last = reverseList2(head->next); // 把这个链表末尾元素的 next 指向 head head->next->next = head; // 把 head->next 指向空指针 head->next = nullptr; return last; }