C++ 12 ms solution


  • 3
    P
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(head == NULL || head->next == NULL) return head;
            ListNode *tail;
            int n=1,j;
            for(tail = head;tail->next!=NULL;tail=tail->next) n++;
            j = (n-k%n)%n;
            tail->next = head;
            for(int i=0;i<j;i++){
                head = head->next;
                tail = tail->next;
            }
            tail->next = NULL;
            return head;
        }
    };

Log in to reply
 

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