Monday, November 25, 2013

LeetCode Problem : Rotate List

Problem


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.

Code

ListNode *rotateRight(ListNode *head, int k) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(!head)
        return head;
    int count  = 0,len = 0;
    ListNode *node3 = head;
    while(node3){
        node3 = node3->next;
        ++len;
    }
    k = k % len;
    if(k == 0)
        return head;
    ListNode *node2 = head;
    while(node2 && count < k){
        node2 = node2->next;
        ++count;
    }
    ListNode *node1 = head;
    while(node2->next){
        node2 = node2->next;
        node1 = node1->next;
    }
    node2->next = head;
    head = node1->next;
    node1->next = 0;
    return head;
}

No comments:

Post a Comment