[LeetCode] 61. 旋转链表

[LeetCode] 61. 旋转链表

题目

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

image

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

思路

设 n 为链表长度,向右旋转 k 个位置,相当于 head 向右移动 n - k%n 个位置。

所以首先将链表首尾相连,然后将 n - k%n 位置前断开,最所返回 n - k%n 位置的节点。

代码

/**
 * 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 == nullptr) return nullptr;
        ListNode* ans;
        ListNode* it = head;
        int cnt = 1;
        while (it->next != nullptr) {
            it = it->next;
            cnt++;
        }
        it->next = head;
        int t = cnt - (k % cnt);
        int i = 1;
        it = head;
        while (i < t) {
            it = it->next;
            i++;
        }
        ans = it->next;
        it->next = nullptr;
        return ans;

    }
};
欢迎转载,转载请注明出处!
原文地址:https://www.cnblogs.com/huihao/p/15425278.html