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;
    }
};
相关推荐
青 .34 分钟前
数据结构---二叉搜索树的实现
c语言·网络·数据结构·算法·链表
MChine慕青1 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
塔中妖2 小时前
【华为OD】查找接口成功率最优时间段
算法·链表·华为od
云:鸢4 小时前
C语言链表设计及应用
c语言·开发语言·数据结构·链表
林木辛4 小时前
LeetCode热题 42.接雨水
算法·leetcode
黑菜钟6 小时前
代码随想录第七天|● 454.四数相加II ● 383. 赎金信 ● 15. 三数之和 18.四数之和
c++·算法·leetcode
pzx_0017 小时前
【LeetCode】14. 最长公共前缀
算法·leetcode·职场和发展
songx_998 小时前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
dragoooon3410 小时前
[数据结构——lesson5.1链表的应用]
数据结构·链表
1白天的黑夜111 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表