返回
Python 算法解析:用优美代码轻松掌握 Leetcode 61 - 旋转链表
后端
2024-02-16 03:23:46
算法概述
旋转链表 是一个经典的链表操作问题,它要求你将一个链表中的元素向右移动 k 个位置。例如,如果链表为 1->2->3->4->5,并且 k = 2,那么旋转后的链表应为 4->5->1->2->3。
解决 leetcode 61 旋转链表问题的基本思路是:
- 遍历链表,找到倒数第 k 个节点。
- 将链表从倒数第 k 个节点处断开,形成两个子链表。
- 将第二个子链表连接到第一个子链表的末尾,形成一个新的链表。
- 返回新的链表。
Python 代码
def rotate_list(head, k):
"""
Rotates a linked list by k positions.
Args:
head: The head of the linked list.
k: The number of positions to rotate the list.
Returns:
The head of the rotated linked list.
"""
# Find the length of the linked list.
length = 0
current = head
while current:
length += 1
current = current.next
# If k is greater than the length of the linked list,
# then we need to rotate the list multiple times.
k %= length
# If k is 0, then the list does not need to be rotated.
if k == 0:
return head
# Find the new head of the linked list.
current = head
for _ in range(k):
current = current.next
# Break the linked list at the new head.
new_head = current
current = head
while current.next != new_head:
current = current.next
current.next = None
# Connect the second half of the linked list to the first half.
current = new_head
while current.next:
current = current.next
current.next = head
# Return the new head of the linked list.
return new_head
复杂度分析
- 时间复杂度:O(n),其中 n 是链表的长度。
- 空间复杂度:O(1),因为我们不需要使用额外的空间。
总结
leetcode 61 旋转链表的问题看似复杂,但它可以通过巧妙的算法技巧来轻松解决。通过使用 Python 语言中链表操作的相关函数,我们可以用优美的代码轻松实现链表的旋转操作。希望这篇解析对你的学习有所帮助。