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;
    }
};
相关推荐
圣保罗的大教堂2 小时前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊3 小时前
LeetCode1881~1990题目解析
java·leetcode
文丑颜不良啊6 小时前
LeetCode1861~1880题目解析
java·leetcode
文丑颜不良啊6 小时前
LeetCode1921~1940题目解析
java·leetcode
一去不复返的通信er9 小时前
排序 + 双指针:力扣15三数之和
算法·leetcode
文丑颜不良啊9 小时前
LeetCode1901~1920题目解析
java·leetcode
Pniubi9 小时前
力扣3无重复字符的最长字串(滑动窗口)
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode1661~1680题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1721~1740题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1681~1700题目解析
java·leetcode