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;
    }
};
相关推荐
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll3 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐3 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶4 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
郝学胜-神的一滴4 天前
深入理解链表:从基础到实践
开发语言·数据结构·c++·算法·链表·架构
im_AMBER4 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了4 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333334 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
网小鱼的学习笔记4 天前
leetcode876:链表的中间结点
数据结构·链表