细节:
- 若 k == 0 (包括取模之后k = 0)时,直接返回原链表即可。
- 注意末尾节点指向None。
# 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
p = head
cnt = 0
while p:
p = p.next
cnt += 1
k = k % cnt
if k == 0:
return head
pre, p = head, head
for i in range(cnt - k):
pre = p
p = p.next
pre.next = None # 末尾节点指向None
res = p
while p.next:
p = p.next
p.next = head
return res