返回

用好闭环法,链表旋转巧完成

前端

链表是一种重要的数据结构,它由一组节点组成,每个节点都包含一个值和指向下一个节点的指针。链表的优势在于它可以在常数时间内进行插入和删除操作,这使得它非常适合存储和处理大量数据。

链表旋转是一种常见的数据结构操作,它将链表中的每个节点向右移动 k 个位置。例如,如果我们有一个链表 1->2->3->4->5,并且我们想将其旋转 2 个位置,那么旋转后的链表将变为 3->4->5->1->2。

有很多种方法可以实现链表旋转,其中一种最有效的方法是使用闭环法。闭环法的工作原理是将链表的最后一个节点连接到链表的第一个节点,形成一个闭环。然后,我们从链表的第 k 个节点开始遍历,并将其设置为新的头节点。最后,我们将链表的最后一个节点的指针指向新的头节点,以断开闭环。

def rotate_list(head, k):
  """
  Rotates a linked list to the right by k positions.

  Args:
    head: The head node of the linked list.
    k: The number of positions to rotate the list.

  Returns:
    The head node of the rotated linked list.
  """

  # Find the length of the linked list.
  length = 0
  current_node = head
  while current_node is not None:
    length += 1
    current_node = current_node.next

  # Handle the case when k is greater than the length of the linked list.
  k = k % length

  # If k is 0, then the linked list does not need to be rotated.
  if k == 0:
    return head

  # Find the new head node.
  new_head = head
  for _ in range(k):
    new_head = new_head.next

  # Connect the last node of the linked list to the first node.
  last_node = head
  while last_node.next is not None:
    last_node = last_node.next
  last_node.next = head

  # Set the new head node.
  head = new_head

  # Disconnect the last node from the first node.
  last_node.next = None

  return head

使用闭环法来实现链表旋转的时间复杂度为 O(n),其中 n 是链表的长度。空间复杂度为 O(1),因为我们不需要使用任何额外的空间。

结语

链表旋转是一种常见的数据结构操作,它有很多种实现方法。闭环法是一种有效的方法,它可以在常数时间内实现链表旋转。这种方法简单易懂,并且可以很容易地扩展到其他链表操作中。