Skip to content

Commit 1b0d88a

Browse files
authoredAug 15, 2023
Create 61. Rotate List
1 parent 7c55b86 commit 1b0d88a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
 

‎61. Rotate List

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
int getLength(ListNode*head){
4+
int len =0;
5+
while(head){
6+
++len;
7+
head= head->next;
8+
}
9+
return len;
10+
}
11+
ListNode* rotateRight(ListNode* head, int k) {
12+
if(!head)return 0;
13+
int len = getLength(head);
14+
int actualRotateK = (k% len);
15+
if(actualRotateK == 0)return head;
16+
int newLastNodepos = len - actualRotateK - 1;
17+
ListNode* newLastNode = head;
18+
for(int i=0;i<newLastNodepos;i++){
19+
newLastNode = newLastNode->next;
20+
}
21+
ListNode*newHead = newLastNode->next;
22+
newLastNode->next = 0;
23+
ListNode*it = newHead;
24+
while(it->next){
25+
it= it->next;
26+
}
27+
it->next = head;
28+
return newHead;
29+
}
30+
};

0 commit comments

Comments
 (0)
Please sign in to comment.