[LeetCode] 61. Rotate List

来源:互联网 发布:单片机花贲浇花 编辑:程序博客网 时间:2024/06/10 18:32

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if (head == nullptr || k == 0) return head;        int n;        ListNode **slow = &head, *fast = head;        for (n = 1; n < k && fast->next != nullptr; n++)            fast = fast->next;        // deal with k >= n        if (fast->next == nullptr) {            k = k % n;            if (k == 0) return head;            fast->next = head;            fast = head;            int headpos = n - k;            for (int i = 1; i < headpos; i++)                fast = fast->next;            ListNode *newhead = fast->next;            fast->next = nullptr;            return newhead;        }        // deal with k < n        while (fast->next) {            slow = &((*slow)->next);            fast = fast->next;        }        ListNode *newhead = *slow;        *slow = nullptr;        fast->next = head;        return newhead;    }};

这里写图片描述
这里写图片描述

原创粉丝点击