No more thing than just carefully C++ implementation.


  • 0
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(!head || !head->next)  return head;
            if(k==0)  return head;
            int len=0;
            ListNode* cur=head;
            while(cur->next) { cur=cur->next; len++; }
            len++;
            k=k%len;
            ListNode* tail=cur;
            cur=head;
            for(int i=0; i<len-k-1; i++) cur=cur->next;
            tail->next=head;
            head=cur->next;
            cur->next=NULL;
            return head;
        }
    };

Log in to reply
 

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