【second】Rotate List

注意一些边界条件

    ListNode *rotateRight(ListNode *head, int k) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(head==NULL)
            return NULL;
        int len = getLength(head);
        k = k%len;
        if(k==0)
            return head;
        ListNode* cur = head;
        for(int i=0;i<len-1-k;i++)
            cur = cur->next;
        ListNode* tail = cur;
        while(tail->next)
            tail = tail->next;
        ListNode* newHead = cur->next;
        cur->next = NULL;
        tail->next = head;
        return newHead;
    }
    
    int getLength(ListNode* head)
    {
        int len = 0;
        while(head)
        {
            ++len;
            head = head->next;
        }
        return len;
    }

  

posted @ 2013-10-18 17:02  summer_zhou  阅读(112)  评论(0编辑  收藏  举报