力扣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;
    }
};
相关推荐
CoovallyAIHub4 分钟前
工业视觉检测:多模态大模型的诱惑
深度学习·算法·计算机视觉
Jayden_Ruan10 分钟前
C++分解质因数
数据结构·c++·算法
bubiyoushang88836 分钟前
MATLAB实现雷达恒虚警检测
数据结构·算法·matlab
wu_asia40 分钟前
编程技巧:如何高效输出特定倍数数列
c语言·数据结构·算法
AlenTech1 小时前
207. 课程表 - 力扣(LeetCode)
算法·leetcode·职场和发展
练习时长一年2 小时前
LeetCode热题100(杨辉三角)
算法·leetcode·职场和发展
lzllzz232 小时前
bellman_ford算法
算法
栈与堆2 小时前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
sunfove2 小时前
麦克斯韦方程组 (Maxwell‘s Equations) 的完整推导
线性代数·算法·矩阵
Rui_Freely2 小时前
Vins-Fusion之 SFM准备篇(十二)
人工智能·算法·计算机视觉