def listmerge(L1, L2):
'''(CustomerNode, CustomerNode) -> CustomerNode
Merge the linked lists headed by L1 and L2 into a single list with ticket_num in
increasing order. Return the head of the merged list.
REQ: Lists headed by L1 and L2 are sorted by ticket_num, all ticket_num values are unique.
'''
current = L1
while current.next != None:
current = current.next
current.next = L2
return L1
客户节点的一个例子就像LinkedList,除了像这样:
list1 = CustomerNode(priority, data, next = None)
基本上我的排序优先级。最低的数字应该是头部。
到目前为止,我刚刚进行了合并。
答案 0 :(得分:1)
我在想,在合并节点之前,您可以先按照要排序的类别进行排序,然后使用listmerge(L1, L2)
函数进行合并。
假设我们有这些节点:
class Node():
def __init__(self, name, data, next=None):
self.name = name
self.data = data
self.next = next
注意:我已将priority
替换为name
现在我要创建一个列表来保存所有这些节点而不进行任何排序:
nodeList = [<__main__.Node object at 0x1021e7320>, <__main__.Node object at 0x1021e7278>, <__main__.Node object at 0x1021e72b0>, <__main__.Node object at 0x1021e7240>, <__main__.Node object at 0x1021e72e8>]
然后我可以按照我要排序的字段进行排序。我将假设按data
排序:
# Helper function
def getData(node):
return node.data
sortedList = sorted(nodeList, key=getData)
最后通过迭代sortedList
并将每个节点传递到listmerge
函数来进行合并。
显示上述结果的示例:
# This is the list full of unordered objects. I want to sort by the data integer values
mynodelist = [Node('a', 10), Node('b', 5), Node('c', 7), Node('d', 20), Node('e', 2)]
sortedList = sorted(mynodelist, key=getData)
for o in sortedList:
print(o.data)
### OUTPUT ###
# 2
# 5
# 7
# 10
# 20