程式語言 - LeetCode - C++ - 61. Rotate List



參考資訊:
https://www.cnblogs.com/grandyang/p/4355505.html

題目:


解答:

/**
 * 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) {
        int n = 1;
        ListNode *p = head;

        if (!head || !head->next || k == 0) {
            return head;
        }

        while (p->next) {
            p = p->next;
            n += 1;
        }
        p->next = head;

        k %= n;
        p = head;
        for (int i = 0; i < n - k - 1; ++i) {
            p = p->next;
        }

        ListNode *r = p->next;
        p->next = nullptr;

        return r;
    }
};