Monday, September 22, 2014

[Leetcode] Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
Analysis:
  • Take the given example, we know the length of the list is 5 and the position to split the list is 3, then we can rotate the list by splitting the list between 3 and 4 and linking the tail and head of the list. The steps would be:

  1. Get the length of the list, l and the tail of the list tail
  2. Get the position p1 and p2 to split the list at l - k%l since k may be greater than l
  3. Get the new head by setting p1->next = NULL, tail->next = head and newhead = p2
  4. Note: if k%l == 0, simply return the head

ListNode *rotateRight(ListNode *head, int k) {
        if (head == NULL)
            return head;
        int len = 0;
        ListNode* curr = head;
        ListNode* tail = NULL;
        while(curr != NULL)
        {
            len++;
            tail = curr;
            curr = curr->next;
        }
        //Note:len could not be 0
        int pos = len - k % len;
        if (pos == len)
            return head;
        curr = head;
        ListNode* prev = NULL;
        for(int i=0; inext;
        }
        
        ListNode* newhead = curr;
        if (prev != NULL) {
            prev->next = NULL;
            tail->next = head;
        }
        
        return newhead;
    }

No comments:

Post a Comment