Skip to content

Commit 1817176

Browse files
committed
Time: 11 ms (34.00%), Space: 11.7 MB (63.68%) - LeetHub
1 parent b374b23 commit 1817176

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

0061-rotate-list/0061-rotate-list.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
int length(ListNode* head){
4+
ListNode* temp=head;
5+
int i = 0;
6+
while(temp){
7+
temp=temp->next;
8+
i++;
9+
}
10+
return i;
11+
}
12+
ListNode* rotateRight(ListNode* head, int k) {
13+
if(head==NULL) return NULL;
14+
int len=length(head);
15+
int actualk=k%len;
16+
if(actualk==0) return head;
17+
18+
int pos=len-actualk-1;
19+
ListNode* newlast=head;
20+
ListNode* newhead=nullptr;
21+
while(pos--){
22+
newlast=newlast->next;
23+
}
24+
newhead=newlast->next;
25+
newlast->next=NULL;
26+
ListNode* it=newhead;
27+
while(it->next!=NULL){
28+
it=it->next;
29+
}
30+
it->next=head;
31+
return newhead;
32+
}
33+
};

0 commit comments

Comments
 (0)