Python 程序:将给定链表按升序排序


假设我们有一个链表。我们需要将该链表按升序排序。

因此,如果输入类似于 [5, 8, 4, 1, 5, 6, 3],则输出将是 [1, 3, 4, 5, 5, 6, 8, ]

为了解决这个问题,我们将遵循以下步骤

  • values := 一个新的列表
  • head := 节点
  • 当节点不为空时,执行以下操作
    • 将节点的值插入到 values 的末尾
    • node := 下一个节点
  • 对列表 values 进行排序
  • values := 通过获取 values 的元素创建一个双端队列
  • node := head
  • 当节点不为空时,执行以下操作
    • 节点的值 := 队列的左端元素,并从队列的左端删除元素
    • node := 下一个节点
  • 返回 head

让我们看一下以下实现,以便更好地理解

示例

在线演示

import collections

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next

def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)

   return head

def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')

class Solution:
   def solve(self, node):

   values = []
   head = node
   while node:
      values.append(node.val)
      node = node.next

   values.sort()
   values = collections.deque(values)

   node = head
   while node:
      node.val = values.popleft()
      node = node.next

   return head

ob = Solution()
head = make_list([5, 8, 4, 1, 5, 6, 3])
print_list(ob.solve(head))

输入

[5, 8, 4, 1, 5, 6, 3]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

[1, 3, 4, 5, 5, 6, 8, ]

更新于: 2020-11-26

4K+ 浏览量

开启你的 职业生涯

完成课程获得认证

开始学习
广告