61. Rotate List

题意: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位,再两个同时向前移,比如对于上面那个例子,slow指向3,fast指向5,再把slow断开,然后用fast指向head就可以了,但是这题其实一个问题,就是k的取值,对于1->2,如果k取3的话,最后的答案应该是2->1,所以对于我这种方法的话,就要先遍历一次列表来求长度,再求余,代码会显得稍微繁琐一点:

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return head
        fast = slow = head
        cnt = 0
        while fast:
            cnt += 1
            fast = fast.next
        fast, k = head, k%cnt
        if not k%cnt:
            return head
        while fast.next:
            if k == 0:
                slow = slow.next
            else:
                k -= 1
            fast = fast.next
        new_head = slow.next
        slow.next = None
        fast.next = head
        return new_head

当然,还看到有一种方法,是直接遍历到结尾,求出长度len,然后让首尾连接成一个环链表,然后再向前移动len-k%len长度,再把next打断就可以了:

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next:
            return head

        n, cur = 1, head
        while cur.next:
            cur = cur.next
            n += 1
        cur.next = head

        cur, tail = head, cur
        for _ in xrange(n - k % n):
            tail = cur
            cur = cur.next
        tail.next = None
        return cur
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值