Rotate List 【要优化】

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.

思路:任何问题都要先检查validation,special case  

注意:【这道题我的速度是18ms,还有要优化的地方。未解决?】

class Solution { 
public:
    ListNode *rotateRight(ListNode *head, int k) {
        //check validation
        if(head==NULL || k==0) return head;
        // special case : only one node
        if(head->next==NULL) return head;
        //compute length, becase we need to figure out :k, lenght, who is bigger?
        int length=0;
        ListNode *p=head;
        while(p){
            length++;
            p=p->next;
        }
        //compute the offset
        int offset=0;
        if(k%length==0) return head;
        else offset=k%length;
        
        int movesteps=length-offset;
        
        //rotate start
        ListNode *phead=head;
        while(--movesteps>0){
            phead=phead->next;
        }
        p=phead;
        phead=phead->next;
        p->next=NULL;
        p=phead;
        
        while(p->next!=NULL) p=p->next;
        p->next=head;
        
        return phead; 

    }
};
原文地址:https://www.cnblogs.com/renrenbinbin/p/4384967.html