Leetcode—61. 旋转链表【中等】

2024每日刷题(114)

Leetcode—61. 旋转链表

Leetcode—61. 旋转链表【中等】_第1张图片

实现代码

/**
 * 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 || head->next == nullptr || k == 0) {
            return head;
        }
        ListNode* tail = head;
        int len = 1;
        for(; tail->next; tail = tail->next) {
            len++;
        }
        // 成环
        tail->next = head;
        int t = len - k % len;
        for(int i = 0; i < t; i++) {
            tail = tail->next;
        }
        ListNode* newNode = tail->next;
        // 断链
        tail->next = nullptr;
        return newNode;
    }
};

运行结果

Leetcode—61. 旋转链表【中等】_第2张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,链表,算法,c++,数据结构,经验分享)