Skip to content

Commit b98cb25

Browse files
committed
Create: 0061-rotate-list.cpp
1 parent 6e3731f commit b98cb25

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

cpp/0061-rotate-list.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Given the head of a linked list, rotate the list to the right by k places.
3+
Example: list = [1,2,3,4,5] and k = 2
4+
Output: [4,5,1,2,3]
5+
6+
Time complexity: O(n)
7+
Space complexity: O(1)
8+
*/
9+
10+
class Solution {
11+
private:
12+
int findLen(ListNode* head){
13+
int len = 0;
14+
while(head!=NULL){
15+
len++;
16+
head = head->next;
17+
}
18+
return len;
19+
}
20+
ListNode* findNewHead(ListNode* head,int k){
21+
int i=0;
22+
while(i+1<k){
23+
i++;
24+
head = head->next;
25+
}
26+
ListNode* ret = head->next;
27+
head->next = NULL;
28+
return ret;
29+
}
30+
ListNode* findLast(ListNode* head){
31+
while(head->next!=NULL) head = head->next;
32+
return head;
33+
}
34+
public:
35+
ListNode* rotateRight(ListNode* head, int k) {
36+
int len = findLen(head); // Finds the length of the Linked List
37+
if(len==0) return head;
38+
k = k%len;
39+
if(k==0) return head;
40+
ListNode* newHead = findNewHead(head,len-k); // Finds the node that is the new head
41+
ListNode* last = findLast(newHead); // Finds the last node from the new head and connects it to the previous head
42+
last->next = head;
43+
return newHead;
44+
}
45+
};

0 commit comments

Comments
 (0)