From 91b8ac05f7354b3effface2eebc263346d13d330 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 4 Nov 2022 16:56:13 +0800 Subject: [PATCH] s0019 --- ...s0019_remove_nth_node_from_end_of_list.hpp | 17 +++++++++++ ...s0019_remove_nth_node_from_end_of_list.cpp | 28 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 include/s0019_remove_nth_node_from_end_of_list.hpp create mode 100644 src/s0019_remove_nth_node_from_end_of_list.cpp diff --git a/include/s0019_remove_nth_node_from_end_of_list.hpp b/include/s0019_remove_nth_node_from_end_of_list.hpp new file mode 100644 index 0000000..95109f4 --- /dev/null +++ b/include/s0019_remove_nth_node_from_end_of_list.hpp @@ -0,0 +1,17 @@ +#ifndef S0019_REMOVE_NTH_NODE_FROM_END_OF_LIST +#define S0019_REMOVE_NTH_NODE_FROM_END_OF_LIST + +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 Solution { + public: + ListNode* removeNthFromEnd(ListNode* head, int n); +}; + +#endif diff --git a/src/s0019_remove_nth_node_from_end_of_list.cpp b/src/s0019_remove_nth_node_from_end_of_list.cpp new file mode 100644 index 0000000..f462fcd --- /dev/null +++ b/src/s0019_remove_nth_node_from_end_of_list.cpp @@ -0,0 +1,28 @@ +#include "s0019_remove_nth_node_from_end_of_list.hpp" + +// 思路一:遍历两次,第一次遍历得到总长度,第二次遍历找出倒数第 n 个 +// 思路二:栈,先进后出,全部入栈后弹出倒数第 n 个把它舍弃掉 +// 思路三:双指针,快指针比慢指针多走 n +// 步,等快指针走到头时,慢指针指向的的就是倒数第 n 个 + +// 双指针实现 +ListNode* Solution::removeNthFromEnd(ListNode* head, int n) { + // 一种常见的处理头指针的方法是添加一个哑指针,这个哑指针指向头指针 + // 这样我们就不需要单独讨论头指针了。 + ListNode dummy(0, head); + ListNode* fast = &dummy; + for (int i{0}; i < n; i++) { + if (fast == nullptr) { + return nullptr; + } else { + fast = fast->next; + } + } + ListNode* slow = &dummy; + while (fast->next != nullptr) { + fast = fast->next; + slow = slow->next; + } + slow->next = slow->next->next; + return dummy.next; +}