75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

61. Rotate List

Brute force

Optimized

Code

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        // edge cases
        if (!head || !head->next || k == 0) return head;

        // compute the length
        ListNode *cur = head;
        int len = 1;
        while (cur->next && ++len)
            cur = cur->next;

        // connect last node to head
        cur->next = head;

        // go till that node
        k = k % len;
        k = len - k;
        while (k--) cur = cur->next;

        // make the node head and break connection
        head = cur->next;
        cur->next = NULL;

        return head;
    }
};