A 8ms C++ Solution with Comments


  • 0
    Y
    ListNode* rotateRight(ListNode* head, int k) {
            ListNode newHead(0);
            newHead.next = head;
            ListNode newhead(0), *fast = head, *slow;
            if(head == NULL || head->next == NULL) return head;
            int count = 1, len = 1;
            // Find the length of the ListNode in case the rotate place is very large
            while(fast->next) {
                len++;
                fast = fast->next;
            }
            // Find the relative place shift based on the ListNode length
            k = len - k%len;
            if(k == 0) return head;
            fast = head;
            count = 1;
            // Find the node ready to rotate
            while(count < k) {
                fast = fast->next;
                count++;
            }
            slow = fast;
            // Find the end of ListNode
            while(fast&&fast->next) fast = fast->next;
            fast->next = newHead.next;
            newHead.next = slow->next;
            slow->next = NULL;
            return newHead.next;
        }
    

Log in to reply
 

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