【leetcode刷题】61 rotate list (Python)

原题链接
https://leetcode.com/problems/rotate-list/

解题思路

  • 首先获取链表长度,并且遍历到最后时返回最后一个node(last_node)
  • 本题中k有可能大于链表长度,因此用k%len(listnode)来表示翻转个数
  • 在确认了翻转个数后,再遍历链表标记处翻转处前的一个node(sub_head)
  • 在head前添加一个node(init)
  • 最后使init指向sub_head.next,last_node指向head,sub_head指向NULL即可
    在这里插入图片描述

代码

class Solution(object):
    def rotateRight(self, head, k):
        if not head:
            return head
        init = ListNode(0)
        init.next = head
        length, last_node = self.countList(head)
        k = k % length
        if k==0:
            return head
        sub_head = self.findNode(head, k ,length)
        init.next = sub_head.next
        sub_head.next = None
        last_node.next = head
        return init.next


    def countList(self, head):
        count = 0
        while head != None:
            count += 1
            if not head.next:
                break
            head = head.next
        return count, head

    def findNode(self, head, k, length):
        sub_start = length - k
        sub_head = head
        while sub_start>1:
            sub_head = sub_head.next
            sub_start -= 1
        return sub_head
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值