Sunday, April 26, 2015

[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.
Analysis: Find the k+1 node from the right, and reorganize the list.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    int getLen(ListNode* head)
    {
        int len = 0;
        while(head)
        {
            len++;
            head = head->next;
        }
        return len;
    }
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return head;
        ListNode *kthNode = head;
        ListNode *p = head;
        k %= getLen(head);
        if(k == 0) return head;
        k++;
        while(p->next)
        {
            if(1 == k)
            {
                kthNode = kthNode->next;
            }
            else k--;
            p = p->next;
        }
        p->next = head;
        ListNode *ret = kthNode->next;
        kthNode->next = NULL;
        return ret;
    }
};