Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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)
Comment on lines +1 to +8
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can be much better! Explain it as if you are explainaing this to a high school student. Also use markdown and try to explain the time and space complexity.

20 changes: 20 additions & 0 deletions Linked Lists/#61-Rotate List-Medium/Solution-Rotate List.cpp
Original file line number Diff line number Diff line change
@@ -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; i<n-(k%n); i++){
temp->next = start;
temp = temp->next;
start = start->next;
}
temp->next = NULL;
return start;
}
};