# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution(object): defrotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ ifnot head: return head # base case
fast, slow, l = head, head, head n = 0 while l: n += 1 l = l.next k %= n # 取模
if k == 0: return head # 若k取模后等于0,那是否旋转链表并无差别,直接返回链表本身
while k: fast = fast.next k -= 1 while fast.next: slow, fast = slow.next, fast.next new_head = slow.next slow.next = None fast.next = head return new_head