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

Rotate List

时间:2017-03-18 22:34:47      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:return   指针   nullptr   turn   init   pre   lis   efi   结束   

思路:先对List进行一次遍历,得到长度,第二次遍历时从(length-k%length)处切开即可,这里需要注意第一次遍历结束后指针停留在最后一个元素处,第二次遍历时这个指针便相当于头指针,方便~

/**
 * 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 == nullptr)
            return nullptr;
            
        ListNode *cur = head;
        int length = 1;
        while(cur->next != nullptr)
        {
            cur = cur->next;
            ++length;
        }
        cur->next = head;
        
        int count = length - k%length;
        while(count>0)
        {
            cur = cur->next;
            --count;
        }
        head = cur->next;
        cur->next = nullptr;
        return head;
    }
};

 

Rotate List

标签:return   指针   nullptr   turn   init   pre   lis   efi   结束   

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

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