LeetCode 61. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


Need to pay attention to the K value. k = k % length

ListNode* rotateRight(ListNode* head, int k) {
        if(!head || !head->next) return head;
        ListNode* tmp = head;
        int length = 0;
        while(tmp) {
            length++;
            tmp = tmp->next;
        }
        k = k % length;           // k might be larger than the length of the linked list.
        if(k == 0) return head;   // remember to check k value
        
        ListNode* fast = head;
        ListNode* slow = head;
        while(k > 0) {
            fast = fast->next;
            k = k - 1;
        }
        while(fast && fast->next) {
            slow = slow->next;
            fast = fast->next;
        }
        ListNode* newHead = slow->next;
        slow->next = NULL;
        fast->next = head;
        return newHead;
    }


你可能感兴趣的:(LeetCode 61. Rotate List)