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;
    }
};
相关推荐
mmmmath_33 小时前
LeetCode.637.二叉树的层平均值
算法·leetcode
Tisfy4 小时前
LeetCode 2913.子数组不同元素数目的平方和 I:第一题先常数很大的O(n^2)
算法·leetcode·题解·模拟·暴力
木井巳5 小时前
【动态规划】三步问题
java·算法·leetcode·动态规划·推荐算法
蛋蛋的就会顺顺的14 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
Navigator_Z16 小时前
LeetCode //C - 1291. Sequential Digits
c语言·算法·leetcode
0+11121 小时前
算法 --栈
算法·leetcode
圣保罗的大教堂21 小时前
leetcode 3723. 数位平方和的最大值 中等
leetcode
浅念-1 天前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
学电子她就能回来吗1 天前
LeetCode Hot 100|滑动窗口专题零基础学习笔记
笔记·学习·leetcode
拾饵9421 天前
面试回答整理(Q1–Q3)
leetcode