终于刷到了链表,不容易啊,在链表上跪了好久
思路,先把链表接成闭环,然后在需要的位置上打开
bingo
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return None
if not head.next:
return head
old_tail = head
n = 1
while old_tail.next:
old_tail = old_tail.next
n += 1
old_tail.next = head
i = 0
new_tail = head
while i < (n - k % n - 1):
new_tail = new_tail.next
i += 1
# print(new_tail.val)
new_head = new_tail.next
new_tail.next = None
return new_head