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

Rotate List

时间:2014-10-26 22:47:08      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

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.

思路:将单链表首尾相连呈环状,再在适当位置断开,具体于代码中;

code:

bubuko.com,布布扣
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(!head)
            return head;
            
        int length=1;
        ListNode *cur=head;
        
        while(cur->next)
        {
            ++length;
            cur=cur->next;
        }
        //become a circle
        cur->next=head;
        
        int count=1;
        cur=head;
        ListNode *ltcur;
        while(cur)
        {
            //using remained:important
            if(count==length-k%length)
            {
                ltcur=cur;
                break;
            }
            ++count;
            cur=cur->next;
        }
        //new head
        cur=ltcur->next;
        //break the circle
        ltcur->next=NULL;
        return cur;
    }
};
View Code

 

Rotate List

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/chengyuz/p/4052734.html

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