Rotate List

https://leetcode.com/problems/rotate-list/description/

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.

Thoughts

右移k位先mod n, 确定实际是右移多少位。k == 0时直接返回head. 前面n - k 个不动,把后面k个移到前面,再把前面n - k个贴到后面。或者和rm n the node一样也是从后数k个,因此想到俩指针先后走解法。

Code

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        int n = 0;
        auto cur = head;
        while (cur != nullptr) {
            ++n;
            cur = cur->next;
        }
        if (!n) return head;
        k = k % n;
        if (k == 0) return head;
        cur = head;
        for (int i = 0; i < n - k - 1; ++i) {
            cur = cur->next;
        }
        auto new_head = cur->next;
        cur->next = nullptr;
        cur = new_head;
        while (cur->next != nullptr) {
            cur = cur->next;
        }
        cur->next = head;
        return new_head;
    }
};

Analysis

做题耗时: 45 min

Errors:

  1. 不知道k能大于len

  2. 当first == null时应直接返回。

时间复杂度O(n). 空间O(1)

Last updated

Was this helpful?