C++ concise solution.


  • 1
    C
    ListNode* rotateRight(ListNode* head, int k) {
        int l = 0;
        ListNode *node = head;
        while (node) {
            l++;
            node = node->next;
        }
        if (!head || k%l == 0)
            return head;
        k %= l;
        ListNode *fast, *slow;
        fast = slow = head;
        for (int i = 0; i < k; i++)
            fast = fast->next;
        while (fast && fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode *res = slow->next;
        slow->next = NULL;
        fast->next = head;
        return res;
    }

Log in to reply
 

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