61. 旋转链表
解法一:
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next: #边界条件
return head
i = head
length = 0
while i:
i = i.next
length += 1 #求链长
k = k % length #跳过重复周期
for _ in range(k): #k轮头插法
i, j = head, head.next.next #i为要移动结点的前驱,j指向i后两位
while j:
i = i.next
j = j.next
#头插
i.next.next = head
head = i.next
i.next = j
return head解法二:
最后更新于