From 03e1a245bcb4071a2b917f3c16b35ffe462b6585 Mon Sep 17 00:00:00 2001 From: Rakesh Roshan Date: Tue, 18 Oct 2022 18:43:57 +0530 Subject: [PATCH] 61. Rotate List --- 61. Rotate List.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 61. Rotate List.cpp diff --git a/61. Rotate List.cpp b/61. Rotate List.cpp new file mode 100644 index 0000000..e531875 --- /dev/null +++ b/61. Rotate List.cpp @@ -0,0 +1,21 @@ +class Solution { + public: + ListNode* rotateRight(ListNode* head, int k) { + if (!head || !head->next || k == 0) + return head; + + ListNode* tail; + int length = 1; + for (tail = head; tail->next; tail = tail->next) + ++length; + tail->next = head; // Circle the list + + const int t = length - k % length; + for (int i = 0; i < t; ++i) + tail = tail->next; + ListNode* newHead = tail->next; + tail->next = nullptr; + + return newHead; + } +};