zoukankan      html  css  js  c++  java
  • 61.Rotate List

    给定一个单链表,以及一个非负整数 k ,求将此链表循环右移 k 个单个后的新链表。

    Input: 1->2->3->4->5->NULL, k = 2
    Output: 4->5->1->2->3->NULL
    Explanation:
    rotate 1 steps to the right: 5->1->2->3->4->NULL
    rotate 2 steps to the right: 4->5->1->2->3->NULL


    思路:
    第一遍先记录链表的长度 n,以及其最后一个节点, 如果 k >n,就取模 k = k % n;如果 k ==0,直接返回,否则,将最后一个节点指向头结点。再对链表走 (n-k)个长度,走完 n-k 长度后,下一个节点就是新的头结点,将当前节点->next = NULL,返回下一个节点head即可。

    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if (!head) return NULL;
            int n = 1, count = 0;
            ListNode* tmp_head = head;
            while (tmp_head->next) {
                tmp_head = tmp_head->next; n++;
            }
            k = k % n;
            if (k == 0) return head;
            tmp_head->next = head;
            while (head) {
                count++;
                if (count == n - k) {
                    tmp_head = head;
                    head = head->next;
                    tmp_head->next = NULL;
                    break;
                }
                head = head->next;
            }
            return head;
        }
    };
  • 相关阅读:
    2020寒假简记
    感知神经网络模型与学习算法
    信息检索模型与评估
    Diffie-Hellman密钥交换
    RSA密码体制
    MySQL基准测试(benchmark)
    MySQL数据引擎
    MySQL 多版本并发控制(MVCC)
    MySQL事务管理
    利用dotnet restore 导入本地 .nupkg 包
  • 原文地址:https://www.cnblogs.com/luo-c/p/12995565.html
Copyright © 2011-2022 走看看