力扣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;
    }
};
相关推荐
蒋星熠3 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
小欣加油4 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream4 小时前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
王璐WL4 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
空白到白4 小时前
机器学习-聚类
人工智能·算法·机器学习·聚类
索迪迈科技4 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
zzzsde5 小时前
【数据结构】队列
数据结构·算法
芒克芒克5 小时前
LeetCode 面试经典 150 题:删除有序数组中的重复项(双指针思想解法详解)
算法
青 .5 小时前
数据结构---二叉搜索树的实现
c语言·网络·数据结构·算法·链表
MChine慕青6 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表