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;
    }
};
相关推荐
shylyly_5 分钟前
list的模拟实现
数据结构·c++·链表·迭代器·list·list的模拟实现
yadanuof22 分钟前
leetcode hot100 图论
leetcode·深度优先·图论
xiao--xin1 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法
wxr的理想之路2 小时前
list链表的使用
c语言·数据结构·链表·list
记得早睡~4 小时前
leetcode654-最大二叉树
javascript·数据结构·算法·leetcode
圣保罗的大教堂4 小时前
leetcode 2070. 每一个查询的最大美丽值 中等
leetcode
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧5 小时前
C语言_数据结构总结6:链式栈
c语言·开发语言·数据结构·算法·链表·visualstudio·visual studio
田梓燊5 小时前
leetcode 95.不同的二叉搜索树 Ⅱ
数据结构·算法·leetcode
孑么8 小时前
力扣 编辑距离
java·数据结构·算法·leetcode·职场和发展·贪心算法·动态规划
Dream it possible!15 小时前
LeetCode 热题 100_字符串解码(71_394_中等_C++)(栈)
c++·算法·leetcode