力扣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;
    }
};
相关推荐
锅挤7 小时前
数据结构复习(第一章):绪论
数据结构·算法
skywalker_117 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
汀、人工智能7 小时前
[特殊字符] 第95课:冗余连接
数据结构·算法·链表·数据库架构··冗余连接
生信研究猿7 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
一只小白0007 小时前
反转单链表模板
数据结构·算法
橘颂TA7 小时前
【笔试】算法的暴力美学——牛客 WY22 :Fibonacci数列
算法
XWalnut8 小时前
LeetCode刷题 day9
java·算法·leetcode
bIo7lyA8v8 小时前
算法稳定性分析中的随机扰动建模的技术9
算法
谢白羽8 小时前
vllm抢占机制详解
算法·vllm
Hello--_--World8 小时前
Vue2的 双端 diff算法 与 Vue3 的 快速diff 算法
前端·vue.js·算法