A refreshing solution in C++, with little trick


  • 1

    Actually we do not have to record the tail and then traverse to the node before the new heading node, we can just directly connect the tail with the old heading node and then move forward till the new heading node, which indeed gives us more clean solution as follows.

    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) 
        {
            if(!head) return head;
            int len = 1;
            ListNode *p = head;
            while(p->next) { len++; p = p->next; }
            p->next = head;
            if(k %= len)
                for(int i = 0; i < len-k; ++i, p=p->next) ; 
            ListNode* newHead = p->next;
            p->next = NULL;
            return newHead;
        }
    };
    

Log in to reply
 

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