My 8ms runtime cpp


  • 0
    X
    ListNode* rotateRight(ListNode* head, int k) {
        if (k <= 0 || !head)
            return head;
        
        ListNode* pHead = head;
        ListNode* pEnd = head;
        ListNode* end = NULL;
        
        int size = 0;
        while (pHead) {    //  get the len of list and the last node
            size++;
            end = pHead;
            pHead = pHead->next;
        }
        int mod = k % size;
        pHead = head;    // pHead back to the start of list
        
        for (int i=0; i<=mod; i++)
            pEnd = pEnd->next;
            
        while (pEnd) {
            pEnd = pEnd->next;
            pHead = pHead->next;
        }
        end->next = head;     
        ListNode* result = pHead->next;    
        pHead->next = NULL;    // break loop
        
        return result;
    }

Log in to reply
 

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