[leetcode] 61. Rotate List

Given a list, rotate the list to the right byk places, where k is non-negative.

For example:

Given1->2->3->4->5->NULL andk = 2,

return
return4->5->1->2->3->NULL.

这道题是循环右移链表,题目难度为Medium。

要循环右移链表,需要找出新的链表头位置,然后将表尾和表头相接,同时将新表尾的next指针置为NULL。找新链表头位置的方法相信大家都知道,就不再详述。k值可能比较大,这样在遍历一遍链表之后获取链表长度,此时计数可能还比k小很多,这样用k取余链表长度得到真正需要右移的次数。这样再按照上面的方法即可完成右移。具体代码:

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head || !k) return head;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* newHead = NULL;
        int cnt = 0;
        while(fast && cnt<k) {
            fast = fast->next;
            cnt++;
        }
        if(!fast) {
            k %= cnt;
            cnt = 0;
            fast = head;
            while(fast && cnt<k) {
                fast = fast->next;
                cnt++;
            }
        }
        while(fast) {
            if(!fast->next) {
                ListNode* tmp = slow;
                fast->next = head;
                newHead = slow->next;
                tmp->next = NULL;
                break;
            }
            fast = fast->next;
            slow = slow->next;
        }
        return newHead;
    }
};
看到有人的代码先把链表首尾相接然后右移,这样代码看起来确实简单很多,不过在k较小时会多遍历一遍链表,所以就不给大家推荐了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值