力扣61. 旋转链表

闭环断裂

  • 思路:
    • 将链表尾部链到头部,在旋转位置断开形成新的头部;
    • 在迭代到尾部的过程中进行计数,计数闭环成环后需要偏移的最小步数(如果是链表 size 的整数倍回到原位置,实际不用旋转);
cpp 复制代码
/**
 * 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 (k == 0 || head == nullptr || head->next == nullptr) {
            return head;
        }

        int size = 1;
        ListNode* it = head;
        // count & mv it to the tail
        while (it->next != nullptr) {
            it = it->next;
            size++;
        }

        int shift = size - k % size;
        if (shift == size) {
            return head;
        }

        // ring back
        it->next = head;
        // then shift to break
        while (shift--) {
            it = it->next;
        }

        ListNode* result = it->next;
        it->next = nullptr;

        return result;
    }
};
相关推荐
你怎么知道我是队长11 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒11 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
纪元A梦13 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_14 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls14 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客14 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌14 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun14 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌14 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
我星期八休息15 小时前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list