diff --git a/2112/211228.cpp b/2112/211228.cpp new file mode 100644 index 0000000..b317a47 --- /dev/null +++ b/2112/211228.cpp @@ -0,0 +1,38 @@ +#include + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode* next; + ListNode() : val(0), next(nullptr) {} + explicit ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode* next) : val(x), next(next) {} + ~ListNode() { delete this->next; } +}; + +class Solution { +public: + static ListNode* middleNode(const ListNode* const head) { + const auto* fast = head; + const auto* slow = fast; + while (fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + } + return const_cast(slow); + } +}; + +int main() { + auto* H = new ListNode(1); + auto* ptr = H; + for (int i = 2; i <= 6; ++i) { + ptr->next = new ListNode(i); + ptr = ptr->next; + } + for (const auto* M = Solution::middleNode(H); M; M = M->next) + std::printf("%d\n", M->val); + delete H; +} \ No newline at end of file diff --git a/2112/CMakeLists.txt b/2112/CMakeLists.txt index c0b2453..91e2cd6 100644 --- a/2112/CMakeLists.txt +++ b/2112/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2112) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2112 211227.cpp) \ No newline at end of file +ADD_EXECUTABLE(2112 211228.cpp) \ No newline at end of file