码迷,mamicode.com
首页 > 其他好文 > 详细

Rotate List

时间:2014-11-16 17:09:16      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   div   on   log   

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;
        
    }
};

 

Rotate List

标签:style   blog   io   color   sp   for   div   on   log   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4101504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!