当前位置: 代码迷 >> 综合 >> leetcoe 61. Rotate List (medium)
  详细解决方案

leetcoe 61. Rotate List (medium)

热度:63   发布时间:2024-01-05 00:29:29.0

连成环,再从n-k处切开就行了
具体实现时注意k要对n取模,注意边界就行

class Solution
{
    
public:ListNode *rotateRight(ListNode *head, int k){
    if (head == nullptr || head->next == nullptr)return head;int n = 1;ListNode *cur = head;while (cur->next != nullptr){
    ++n;cur = cur->next;}k %= n;cur->next = head;cur = head;for (int i = 0; i < (n - k - 1); i++){
    cur = cur->next;}head = cur->next;cur->next = nullptr;return head;}
};
  相关解决方案