Rotate List

Q: 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.

A: 要注意k=0,k>=n等这些特殊情况。

为了防止k>>n的情况,先计算链表的长度n,然后对k取余数

    ListNode *rotateRight(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!head||!head->next||k==0)
          return head;
          
        int n = 0;
        ListNode *fast = head;
        while(fast)
        {
            n++;
            fast = fast->next;
        }
        
        if((k = k%n)==0)
          return head;
          
        fast = head;
        ListNode *slow;
        int count = 0;
        while(count<k)
        {
            fast = fast->next;
            count++;
        }
        
        slow = head;
        while(fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }
        
        fast->next = head;
        head = slow->next;
        slow->next = NULL;
        
        return head;
    }

 

posted @ 2013-06-16 14:40  summer_zhou  阅读(114)  评论(0编辑  收藏  举报