Leetcode 61. Rotate List

topic link

Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL

I feel like I'm stuck when I'm doing this question~

The first idea is to use two pointers, the first pointer p points to the current node, the second pointer q points to the position after rotate, after q->val=p->val, update p to q to continue the above process, It might be clearer to look at the picture below: .
May

It looks like the result is correct too. I tested it myself and found that it didn't work. For example: when there are 6 nodes (numbered 1, 2, 3, 4, 5, 6), and k=2, only 1, 3, and 5 nodes will be accessed but 2, 4, and 6 will not be accessed. This is clearly wrong.
Think again. Since every time I jump k positions, there will be a problem that elements are not accessed, so I jump 1 position at a time, and I jump k times, right? Tried it and sure enough AC. I took a look at the submission of this question. The time-consuming and everyone else are on the same order of magnitude. I still clicked and looked at the code of the first place, and then I felt that I was a fool...

In fact there is no need to actually move at all. Just move the head back by list_length-(k%list_length) positions, and then process the old and new tails~

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (k==0||head==NULL) return head;

        ListNode fa(-1);
        fa.next = head;

        int len = 1;
        ListNode* last = head;
        while (last->next){
            ++len;
            last = last->next;
        }
        k %= len;
        k = len -k;
        last->next = head;
        ListNode* pre = &fa, *newHead = head;
        for (int i = 0;i < k;++i){
            newHead = newHead->next;
            pre = pre->next;
        }
        pre->next = NULL;

        ListNode* p = newHead;
        return newHead;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325518727&siteId=291194637