Friday, April 11, 2014

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.
Solution:
Need to consider the case when K is greater than thee list length. Left is straight forward.
Code:
ListNode *rotateRight(ListNode *head, int k) {
    if (!head || !head->next)
        return head;

     int t =1;
     ListNode * cnt = head;
     while(cnt->next)
     {
         cnt = cnt->next;
         t++;
     }

     if (k%t==0)
        return head;

    k = k%t;

    ListNode *first=head;
    ListNode *second=head;

    while(k>0)
    {
        second=second->next;
        k--;
    }

    while(second->next)
    {
        first = first->next;
        second = second->next;
    }

    second->next = head;
    head = first->next;
    first->next = NULL;

    return head;
}

No comments:

Post a Comment