程序在python中将给定的链表按升序排序
假设我们有一个链表。我们必须将列表按升序排序。
因此,如果输入像[5、8、4、1、5、6、3],则输出将为[1、3、4、5、5、6、8,]
为了解决这个问题,我们将按照以下步骤操作:
值:=一个新列表
头:=节点
当节点不为空时,执行
在值的末尾插入节点的值
节点:=节点的下一个
排序列表值
values:=通过获取value元素来构成双头队列
节点:=头
当节点不为空时,执行
节点的值:=队列的左侧元素,并从队列的左侧删除元素
节点:=节点的下一个
回头
让我们看下面的实现以更好地理解:
示例
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]
输出结果
[1, 3, 4, 5, 5, 6, 8, ]
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短