Leetcode 61. Rotate List

题目链接

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

感觉做这道题的时候思路被禁锢了~

首先的思路是用两个指针做,第一个指针p指向当前节点,第二个指针q指向rotate后的位置,q->val=p->val后,将p更新为q继续上述过程,看下图可能更清楚一点:.
maio

看起来结果也是对的。自己测试了一发发现这样做是行不通的。例如:当有6个节点(编号为1,2,3,4,5,6),k=2的时候,只会访问1,3,5节点而不会访问到2,4,6。这显然是错的。
再想。既然每次跳k个位置会有元素未访问的问题,那我每次跳1个位置,跳k次行了吧?试了一下果然AC了。看了一下这道题的提交情况,耗时和大家都是一个量级的,还是点开看了看第一名的代码,然后就觉得自己是傻逼了……

事实上根本不需要真的移动。只需要把head向后移动list_length-(k%list_length)个位置、然后把旧尾和新尾处理一下就可以~

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;
    }
};

猜你喜欢

转载自blog.csdn.net/guojunxiu/article/details/79905562