Thursday, September 12, 2013

[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.



In the example, get p => 4, head =>1, 5 => last, 3=>prev


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

No comments:

Post a Comment