diff --git a/Linked Lists/#61-Rotate List-Medium/Explanation-Rotate List.md b/Linked Lists/#61-Rotate List-Medium/Explanation-Rotate List.md new file mode 100644 index 0000000..6efc5e3 --- /dev/null +++ b/Linked Lists/#61-Rotate List-Medium/Explanation-Rotate List.md @@ -0,0 +1,8 @@ +Rotate a list by k elements. + +Very straightforward by connecting tail node to the head. + +Find k mod n rotations by moving the head pointer, and then finally disconnecting the tail from the current head. + +Time Complexity: O(n) +Space Complexity: O(1) diff --git a/Linked Lists/#61-Rotate List-Medium/Solution-Rotate List.cpp b/Linked Lists/#61-Rotate List-Medium/Solution-Rotate List.cpp new file mode 100644 index 0000000..42a6f04 --- /dev/null +++ b/Linked Lists/#61-Rotate List-Medium/Solution-Rotate List.cpp @@ -0,0 +1,20 @@ +class Solution { + public: + ListNode* rotateRight(ListNode* head, int k){ + if(head == NULL) return NULL; + int n = 1; + ListNode* temp = head; + while(temp->next != NULL){ + temp = temp -> next; + n++; + } + ListNode* start = head; + for(int i=0; inext = start; + temp = temp->next; + start = start->next; + } + temp->next = NULL; + return start; + } + }; \ No newline at end of file