【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

猜你喜欢

转载自blog.csdn.net/weixin_39746008/article/details/89488346