Python 如何对链接列表进行排序?

Python 如何对链接列表进行排序?,python,linked-list,Python,Linked List,客户节点的示例类似于LinkedList,不同之处在于: 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.

客户节点的示例类似于LinkedList,不同之处在于:

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
基本上我会优先排序。最低的数字应该是头部


到目前为止,我只是进行了合并。

我在想,在合并节点之前,您可以先按您想要排序的类别进行排序,然后使用
listmerge(L1,L2)
函数进行合并

假设我们有以下节点:

list1 = CustomerNode(priority, data, next = None)
注意:我已将
优先级
替换为
名称

现在,我将创建一个列表,其中包含所有这些节点,而不进行任何排序:

class Node():
    def __init__(self, name, data, next=None):
        self.name = name
        self.data = data
        self.next = next
最后,通过迭代
sortedList
并将每个节点传递到
listmerge
函数来进行合并

要显示上述结果的示例,请执行以下操作:

# Helper function
def getData(node):
    return node.data

sortedList = sorted(nodeList, key=getData)

您可以遍历节点,找到最低的节点并使其成为头部,从上一个节点删除其引用并将其更改为当前节点的下一个,然后重复。您还可以构建一个具有优先级和节点的元组列表,按优先级排序,然后链接它们。@Ali89-yup-np:)
# Helper function
def getData(node):
    return node.data

sortedList = sorted(nodeList, key=getData)
# 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