Saturday, November 29, 2014

Rotate List

ListNode *rotateRight(ListNode *head, int k) {
    if (!head) return NULL;
    ListNode* tail = head;
    int count = 1;
    while (tail->next)
    {
        tail = tail->next;
        count++;
    }
    k = k % count; // in case the list rotates more than one round.
    if (k == 0) return head;
    ListNode* cur = head;
    for (int i = 0; i < count - k - 1; i++)
        cur = cur->next;
    ListNode* newHead = cur->next;
    cur->next = NULL;
    tail->next = head;
    return newHead;
}

No comments:

Post a Comment