LeetCode 61 Rotate List (Python)

Posted by 小明MaxMing on October 7, 2020

题目

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

解题思路

首先将将链表变成环,同时计算出一共有多少个结点,然后移动到(n-k%n-1)这个节点,其后一个节点为结果,并把这个节点的next指针变为空

代码

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next: 
            return head
        
        tail = head
        n = 1
        while head.next :
            head = head.next
            n += 1
        head.next = tail
        head = head.next
        
        for i in range(n - k % n - 1):
            head = head.next
        res = head.next
        head.next = None
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅