My C++ solution(8ms)


  • -1
    M
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(head==NULL || head->next== NULL) return head;
            int i = 0;
            ListNode *ptr_t = head;
            while(ptr_t->next !=NULL && i<k)
            {
                ptr_t = ptr_t->next;
                i++;
            }
            if(i<k)//k is greater than length of list
            {
                k = k%(i+1);
                if(k == 0) return head;
                else
                {
                    i = 0;
                    ptr_t = head;
                    while(ptr_t->next !=NULL && i<k)
                    {
                        ptr_t = ptr_t->next;
                        i++;
                    }
                }
            }
            ListNode *ptr_h = head;
            while(ptr_t->next!=NULL)
            {
                ptr_h = ptr_h->next;
                ptr_t = ptr_t->next;
            }
            ptr_t->next = head;
            head = ptr_h->next;
            ptr_h->next = NULL;
            return head;
            
        }
    };

Log in to reply
 

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