Sharing my 8ms C++ solution


  • 5
    T
    /**
     * 1) connect the head with the tail, and form a closed circle
     * 2) rotate (n-k%n) times
     * 3) find the new head and tail, break them apart, and return the new head
     */
     
    class Solution{
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(head==NULL || head->next==NULL)
                return head;
                
            ListNode* last;
            int n = 1;
            ListNode* p = head;
            while(p->next)
            {
                n++;
                p=p->next;
            }
            p->next = head;
            last = p;
            k = k%n;
            k = n-k;
            ListNode* current = head;
            for(int i=0; i<k; i++)
            {
                last = current;
                current = current->next;
            }
            
            last->next = NULL;
            return current;
        }
    };

Log in to reply
 

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