An accepted C++ solution


  • -2
    M

    Find the tail of the list... make the tail the new head.
    Repeat k times.

      class Solution {
    public:
        ListNode *rotateRight(ListNode *head, int k) {
            
            if ((head == NULL) || (head->next == NULL) || (k == 0)) {
                return head;
            }
            
            ListNode * prev = head;
            ListNode * tail = head;
            
            while (k > 0)
            {
                while (tail->next != NULL)
                {
                    prev = tail;
                    tail = tail->next;
                }
                
                tail->next = head;
                prev->next = NULL;
                head = tail;
                k--;
            }
            return head;
        }
    };

  • 0
    Z

    code is concise, but complexity is high, need to scan k times list O(kn)


Log in to reply
 

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