zoukankan      html  css  js  c++  java
  • [LeetCode] 61. 旋转链表

    [LeetCode] 61. 旋转链表

    题目

    Given the head of a linked list, rotate the list to the right by k places.

    Example 1:

    image

    Input: head = [1,2,3,4,5], k = 2
    Output: [4,5,1,2,3]

    思路

    设 n 为链表长度,向右旋转 k 个位置,相当于 head 向右移动 n - k%n 个位置。

    所以首先将链表首尾相连,然后将 n - k%n 位置前断开,最所返回 n - k%n 位置的节点。

    代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if (head == nullptr) return nullptr;
            ListNode* ans;
            ListNode* it = head;
            int cnt = 1;
            while (it->next != nullptr) {
                it = it->next;
                cnt++;
            }
            it->next = head;
            int t = cnt - (k % cnt);
            int i = 1;
            it = head;
            while (i < t) {
                it = it->next;
                i++;
            }
            ans = it->next;
            it->next = nullptr;
            return ans;
    
        }
    };
    
    欢迎转载,转载请注明出处!
  • 相关阅读:
    python标准库学习-SimpleHTTPServer
    迁移cnblog博客
    zabbix监控使用
    20 个 OpenSSH 最佳安全实践
    编写基本的 udev 规则
    Linux.Siggen.180
    在 CentOS 7.0 上安装配置 Ceph 存储
    常用 GDB 命令中文速览
    Kubernetes TLS认证
    音乐下载api
  • 原文地址:https://www.cnblogs.com/huihao/p/15425278.html
Copyright © 2011-2022 走看看