12ms with pointers


  • 0
    D
    class Solution {
    public:
    ListNode* rotateRight(ListNode* head, int k) {
        int i;
        int size=0;
        
        if(head==NULL) return NULL;
        if(k==0) return head;
    
        ListNode *end,*prev_end,*pre_head;
        end=head;
        
        /* make it cycle */
        while(end!=NULL)
        {
            prev_end=end;
            end=end->next;
            size++;
        }
    
        prev_end->next=head;
        pre_head=prev_end;
    
        for(i=1;i<=(size-k%size);i++)
            {
            head=head->next;
            pre_head=pre_head->next;
            }
        
        pre_head->next=NULL;    
        return head;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.