lurenaa的博客

👺

连成环,然后改变头部位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head || !head->next) return head;
int count = 0;
auto h = head;
while(h->next) {
h = h->next;
++count;
}
++count;
// cout << count << endl;
h->next = head;
k = k % count;
auto new_tail = head;
int move = count - k;
// cout << move << endl;
for(; move > 0 ; --move) {
if(move == 1) {
auto nx = new_tail->next;
new_tail->next = nullptr;
new_tail = nx;
} else
new_tail = new_tail->next;
}
return new_tail;
}
};

Accepted

231/231 cases passed (4 ms)

Your runtime beats 98.6 % of cpp submissions

Your memory usage beats 18.66 % of cpp submissions (9 MB)