6ms, beat 100% Cppsubmission


  • 0
    S
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(head == NULL || k == 0 || head->next == NULL) return head;
            ListNode* temp = head;
            
            // length should begin with 1
            int length = 1;
            while(temp->next != NULL){
                temp = temp->next;
                length++;
            }
            
            // this is the trick place, the test case includes k > length condion, we need to use %
            int n = length - k % length;
            if(length == n) return head;
            
            // find the new head
            ListNode* h = head;
            for(int i = 1; i < n; i++){
                h = h->next;
            }
            ListNode* newhead = h->next;
            h->next = NULL;
            
            // find the old list tail, and link the tail to head.
            ListNode* p = newhead;
            while(p->next != NULL) p = p->next;
            p->next = head;
            
            return newhead;
        }
    };

Log in to reply
 

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