From 7bc754ae039218b77ff69deb8f29256b50238f62 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 2 Dec 2022 16:06:34 +0800 Subject: [PATCH] s0206 --- include/s0206_reverse_linked_list.hpp | 18 +++++++++++++ src/s0206_reverse_linked_list.cpp | 37 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 include/s0206_reverse_linked_list.hpp create mode 100644 src/s0206_reverse_linked_list.cpp diff --git a/include/s0206_reverse_linked_list.hpp b/include/s0206_reverse_linked_list.hpp new file mode 100644 index 0000000..664ed85 --- /dev/null +++ b/include/s0206_reverse_linked_list.hpp @@ -0,0 +1,18 @@ +#ifndef S0206_REVERSE_LINKED_LIST_HPP +#define S0206_REVERSE_LINKED_LIST_HPP + +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 S0206 { + public: + ListNode* reverseList1(ListNode* head); + ListNode* reverseList2(ListNode* head); +}; + +#endif diff --git a/src/s0206_reverse_linked_list.cpp b/src/s0206_reverse_linked_list.cpp new file mode 100644 index 0000000..c623529 --- /dev/null +++ b/src/s0206_reverse_linked_list.cpp @@ -0,0 +1,37 @@ +#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; +}