C/C++ Solution,at most 2 iterations through the whole linked-list.[Two pointers]


  • 0
    M

    Just done using the hint given by the problem.Pretty easy to understand.:

    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(!head)return nullptr;
            PTR1:
            if(k == 0)return head;
            ListNode *fast,*slow,*tail;
            fast = head;
            slow = nullptr;
            int counter = 0;
            while(fast){
                counter++;
                if(slow)slow=slow->next;
                if(counter > k && !slow)slow = head;
                tail = fast;
                fast = fast->next;
            }
            if(!slow){ //For lazy shrink k.
                k %= counter;
                goto PTR1;
            }
            ListNode *nHead;
            tail->next = head;
            nHead = slow->next;
            slow->next = nullptr;
            return nHead;
        }
    };

Log in to reply
 

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