leetCode61. 旋转链表

leetCode61. 旋转链表

题目思路:见如图所示

代码展示

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(!head) return head;

        int n; // 找出链表长度
        ListNode* tail; // 找到尾结点
        for(auto p = head; p; p = p->next){
            tail = p;
            n++;
        }

        // k的值可能大于n,我们要去取有效的
        k %= n;
        if(k == 0) return head;

        auto p = head;
        for(int i = 0; i < n - k - 1; i++) p = p->next;

        tail->next = head;
        head = p->next;
        p->next = nullptr;

        return head;
    }
};
相关推荐
雾月5529 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++1 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
এ᭄画画的北北2 小时前
力扣-160.相交链表
算法·leetcode·链表
mit6.8246 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
凯子坚持 c8 小时前
深度解析之算法之分治(快排)
算法·leetcode·职场和发展
石去皿13 小时前
力扣hot100 91-100记录
算法·leetcode·职场和发展
圣保罗的大教堂15 小时前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC15 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH15 小时前
数组理论基础
笔记·leetcode·c·数组
2301_8076114916 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯