利用快慢指针,由于 k 的长度可能大于链表的长度,先求出链表长度l,k = k % l,快指针前行 k 步,然后遍历快慢指针

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def linked_list_legth(self, head: ListNode) -> int:
        length = 0
        while head:
            length += 1
            head = head.next
        return length
        
    def rotateLinkedList(self , head: ListNode, k: int) -> ListNode:
        # write code here
        if not head or not head.next:
            return head
        l = self.linked_list_legth(head)
        k = k % l
        if k == 0:
            return head
        fast, slow = head, head
        tail_p, head_p = ListNode(-1), ListNode(-1)
        head_p.next = slow
        i = 0
        while i < k:
            fast = fast.next
            i += 1
        while fast.next and slow.next:
            fast = fast.next
            slow = slow.next
        tail_p.next = slow.next
        slow.next = fast.next
        fast.next = head_p.next
        return tail_p.next