From 1b506210f8af6ab15ce8cb3514d969bc3aee567f Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sun, 13 Mar 2022 14:12:00 +0800 Subject: [PATCH] add: 220311 [cpp] --- cpp/2203/220311.cpp | 62 +++++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220311.cpp diff --git a/cpp/2203/220311.cpp b/cpp/2203/220311.cpp new file mode 100644 index 0000000..c8f615b --- /dev/null +++ b/cpp/2203/220311.cpp @@ -0,0 +1,62 @@ +#include + +/** + * Definition for singly-linked list. + */ + +struct ListNode { + int val; + ListNode* next; + + explicit ListNode(int x = 0, ListNode* next = nullptr) : val(x), next(next) {} +}; + +ListNode* construct(int x) { + return new ListNode(x); +} + +template +ListNode* construct(int x, Ts... xs) { + return new ListNode(x, construct(xs...)); +} + +/** + * 61. Rotate List + * Given the head of a linked list, rotate the list to the right by k places. + */ + +class Solution { +public: + static ListNode* rotateRight(ListNode* head, int k) { + if (!head || !head->next) + return head; + + int n = 0; + for (auto* ptr = head; ptr; ptr = ptr->next) + ++n; + int adv = (n - (k % n)) % n; + + auto* ptr = head; + for (int i = 0; i < adv; ++i) + ptr = ptr->next; + auto* ptr2 = ptr; + while (ptr2->next) + ptr2 = ptr2->next; + ptr2->next = head; + for (auto* ptr3 = head;; ptr3 = ptr3->next) { + if (ptr3->next == ptr) { + ptr3->next = nullptr; + break; + } + } + return ptr; + } +}; + +int main() { + auto* head = construct(1,2); + head = Solution::rotateRight(head, 0); + for (auto* ptr = head; ptr; ptr = ptr->next) + std::cout << ptr->val << " "; + return 0; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index 1170890..76e03c7 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220311-CN.cpp) +ADD_EXECUTABLE(2203 220311.cpp)