Sunday, May 11, 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.


The solution is clear. Keep a count of the list and find out how many nodes we need to move at last. If k is equal to 0, then we don't need to move any node. Otherwise, we need to move count - (k % count) nodes.

C++ Code:

/*
 * func: rotate_right
 * goal: rotate the list to the right by k places
 * @param head: head pointer of the list
 * @param k: input k
 * return: new head node
 */
ListNode* rotate_right(ListNode *head, int k){
    int count = 0;
    //Count the number of nodes in the list
    ListNode *iter = head;
    ListNode *tail_node = nullptr;
    while(iter != nullptr){
        ++count;
        tail_node = iter;
        iter = iter->next;
        
    }
    if(count == 0 || k % count == 0){
        return head;
    }
    
    k = k % count;
    iter = head;
    //Get the new head
    int move_count = 1;
    while(move_count < count - k){
        ++move_count;
        iter = iter->next;
    }
    //Set the new head
    ListNode *new_head = iter->next;
    iter->next = nullptr;
    tail_node->next = head;
    
    return new_head;
    
}

Python Code:

# func: rotate the list to the right by k places
# @param head: head node of the linked list
# @param k: given number k
# @return: new head of the linked list
def rotate_right(head, k):
    if not head or k <= 0:
        return head
    iter = head
    count = 1
    length = 0
    while iter:
        #Get the count of the list and find the number of nodes needed to be moved
        if not iter.next:
            iter.next = head
            length = count
            count = 0
            k = length - k % length
        elif length != 0 and count == k:
            break
        count += 1
        iter = iter.next
    #Set the new head
    head = iter.next
    iter.next = None
    return head

No comments:

Post a Comment