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;
    }
};
相关推荐
小白菜又菜12 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
songyuc15 小时前
BM2『链表内指定区间反转』学习笔记
学习·链表
摸个小yu16 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
skywalker_1117 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
汀、人工智能18 小时前
[特殊字符] 第95课:冗余连接
数据结构·算法·链表·数据库架构··冗余连接
生信研究猿18 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
XWalnut18 小时前
LeetCode刷题 day9
java·算法·leetcode
零二年的冬18 小时前
epoll详解
java·linux·开发语言·c++·链表
6Hzlia18 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
宵时待雨19 小时前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode