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.

分析:此题问的不是很明确,所以理解题意很重要,特别是k大于list长度的时候。

class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(head == NULL || head->next == NULL) return head;
        
        int len = 0;
        for(ListNode * p = head; p; p = p->next, len++);
        
        if(len == k) return head;
        
        k = k%len;
        
        if(k == 0) return head;
        
        ListNode * first = head, *second = head;
        for(int i = 0; i < k-1; i++,second = second->next);
        
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        
        ListNode * pre_first = dummy;
        while(second->next){
            pre_first = first;
            first = first->next;
            second = second->next;
        }
        
        second->next = dummy->next;
        pre_first->next = NULL;
        dummy->next = first;
        
        return dummy->next;
        
    }
};

 

posted on 2014-11-16 15:59  Ryan-Xing  阅读(196)  评论(0编辑  收藏  举报