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.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL) return NULL;
        ListNode* dummy=new ListNode(-1);
        dummy->next=head;
        ListNode *tail=getRightk(dummy,k);
        if(tail==dummy) return head;
        dummy->next=tail->next;
        ListNode *tmp=tail;
        while(tmp->next){
            tmp=tmp->next;
        }
        tmp->next=head;
        tail->next=NULL;
        return dummy->next;
    }
    ListNode* getRightk(ListNode* dummy,int k){
        ListNode* right=dummy->next;
        ListNode* left=dummy->next;
        ListNode* leftpre=dummy;
        
        int length=0;
        ListNode* tmp=dummy->next;
        while(tmp){
            length++;
            tmp=tmp->next;
        }
        
        if(k%length==0) return dummy;
        for(int i=0;i<k%length;i++){
            right=right->next;
        }
        while(right!=NULL){
            right=right->next;
            leftpre=leftpre->next;
        }
        return leftpre;
    }
};


你可能感兴趣的:(Rotate List)