From 3706cbe5b671f7cb71c98d92218a277a33b2fbab Mon Sep 17 00:00:00 2001 From: striver79 <47192562+striver79@users.noreply.github.com> Date: Sat, 2 Oct 2021 03:29:21 +0530 Subject: [PATCH] Create rotateListCpp --- rotateListCpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 rotateListCpp diff --git a/rotateListCpp b/rotateListCpp new file mode 100644 index 0000000..ddc6b0e --- /dev/null +++ b/rotateListCpp @@ -0,0 +1,35 @@ +/** + * 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: + ListNode* rotateRight(ListNode* head, int k) { + // edge cases + if (!head || !head->next || k == 0) return head; + + // compute the length + ListNode *cur = head; + int len = 1; + while (cur->next && ++len) + cur = cur->next; + + // go till that node + cur->next = head; + k = len - k % len; + while (k--) cur = cur->next; + + // make the node head and break connection + head = cur->next; + cur->next = NULL; + + + return head; + } +};