61. 旋转链表 - 力扣(LeetCode)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:if not head or not head.next or k == 0:return head# 计算链表长度length = 1current = headwhile current.next:current = current.nextlength += 1# 将链表变成环current.next = head# 计算新的头节点位置k = k % length # 如果 k >= length,则只需移动 k % length 步steps_to_new_head = length - k# 找到新的头节点并断开环new_tail = headfor _ in range(steps_to_new_head - 1):new_tail = new_tail.nextnew_head = new_tail.nextnew_tail.next = Nonereturn new_head