
将链表的首尾相连,然后新链表的头结点,断开即可

# 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 head is None or head.next is None:
return head
cur = head
n = 1
while cur.next:
cur = cur.next
n = n + 1
cur.next = head
count = n - k % n
while count > 0:
cur = cur.next
count = count - 1
newNode = cur.next
cur.next = None
return newNode
本文深入探讨了链表旋转算法的实现细节,通过将链表首尾相连再断开的方式,实现了链表的右旋转。文章提供了完整的Python代码示例,帮助读者理解并掌握这一重要的数据结构操作。
584

被折叠的 条评论
为什么被折叠?



