力扣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;
    }
};
相关推荐
浊酒南街21 分钟前
XGBClassifiler函数介绍
算法·机器学习·xgb
mlxg9999927 分钟前
hom_mat2d_to_affine_par 的c#实现
算法·计算机视觉·c#
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧3 小时前
C语言_数据结构总结8:链式队列
c语言·开发语言·数据结构·链表·visualstudio·visual studio
真就死难4 小时前
完全日期(日期枚举问题)--- 数学性质题型
算法·日期枚举
不知道取啥耶5 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
花间流风5 小时前
晏殊几何学讲义
算法·矩阵·几何学·情感分析
@心都5 小时前
机器学习数学基础:42.AMOS 结构方程模型(SEM)分析的系统流程
人工智能·算法·机器学习
tt5555555555556 小时前
每日一题——三道链表简单题:回文,环形合并有序
数据结构·链表
我想吃烤肉肉6 小时前
leetcode-sql数据库面试题冲刺(高频SQL五十题)
数据库·sql·leetcode
小六子成长记7 小时前
C语言数据结构之顺序表
数据结构·链表