Are there any better answers?


  • 0
    Z
     ListNode * rotateRight  (ListNode *head, int k) {
    
        if ((!head)  || (!head->next) || (k == 0))
    
            return head;
    
        ListNode *p, *q;
        int m, n;
        m = k;
        n = 0;
        p = q = head;
        while(m && p)
        {
            p = p->next;
            m--;
            n++;
        }
    
        if(!p)
        {
            n = k % n;
            if(n == 0)
                return head;
            p = head;
            while(n)
            {
               p = p->next;
               n--;
            }
        }
        while(p->next)
        {
            q = q->next;
            p = p->next;
        }
        p->next = head;
        head = q->next;
        q->next =NULL;
        return head;
        
     }

Log in to reply
 

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