From 400defd81281c8feb267beeff31e394e4fc8559c Mon Sep 17 00:00:00 2001 From: Gabriel Donnan <47415809+gabedonnan@users.noreply.github.com> Date: Thu, 30 Mar 2023 12:07:48 +0100 Subject: [PATCH] Create rotate-list.cpp beats 96.7 --- rotate-list.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 rotate-list.cpp diff --git a/rotate-list.cpp b/rotate-list.cpp new file mode 100644 index 0000000..1cde01c --- /dev/null +++ b/rotate-list.cpp @@ -0,0 +1,47 @@ +/** + * Definition for singly-linked 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: + int getListLength(ListNode* curr) { + int fin = 0; + while (curr != NULL) { + fin++; + curr = curr->next; + } + return fin; + } + + ListNode* rotateRight(ListNode* head, int k) { + int len = getListLength(head); + if (len == 0) { + return head; + } + k = k % len; + if (k == 0) { + return head; + } + + ListNode* secondHalfTail = head; + for (int i = 0; i < (len - 1) - k; i++) { + secondHalfTail = secondHalfTail->next; + } + + + ListNode* firstHalfHead = secondHalfTail->next; + ListNode* finalVal = firstHalfHead; + secondHalfTail->next = NULL; + while (firstHalfHead->next != NULL) { + firstHalfHead = firstHalfHead->next; + } + firstHalfHead->next = head; + return finalVal; + } +};