Solution in C ~ Time Complexity O(n)


  • 0
    B
    struct ListNode* rotateRight(struct ListNode* head, int k) {
        
        if(head == NULL || head->next == NULL || k == 0) return head;
        
        struct ListNode* tail = head;
        struct ListNode* p = head;
        int length = 0;
        
        while(tail->next != NULL) {
            tail = tail->next;
            length++;
        }
        
        k = k % (length+1);
        
        tail->next = head;
        
        for(int i = 0; i < length - k; i++) 
            p = p->next;
        
        head = p->next;
        p->next = NULL;
        return head;
    }
    

Log in to reply
 

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