python—查看给定代码中的sortlist(…)函数在对元素进行排序并将其推入另一个ll之后,其顺序被提升为什么?

shstlldc  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(274)

问题陈述:给定一个由n个节点组成的链表l。对链接列表进行排序。
示例:输入:1->-2->-3->4->-5输出:-5->-3->-2->1->4
但是当我运行代码时,我得到了输出:对于输入:1-2-3 4-5
你的输出是:1-2-34-5
但我认为我的代码在逻辑上是正确的。我错过了什么。此外,我只能对sortlist函数进行编辑,因为其余的代码都是样板代码。

def sortList(head):
    temp=head
    arr=[]
    while temp!=None:
        arr.append(temp.data)
        temp=temp.next
    arr.sort()
    ll1=LinkedList()
    for i in arr:
        ll1.append(i)
    return ll1.head

# Initial Template for Python 3

class Node:
    def __init__(self, data):   # data -> value stored in node
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, new_value):
        new_node = Node(new_value)
        if self.head is None:
            self.head = new_node
            return
        curr_node = self.head
        while curr_node.next is not None:
            curr_node = curr_node.next
        curr_node.next = new_node

def PrintList(head):
    while head:
        print(head.data,end=' ')
        head=head.next

if __name__ == '__main__':
    t=int(input())
    for cases in range(t):

        n=int(input())
        ll = LinkedList() # create a new linked list 'll'.
        nodes_ll = list(map(int, input().strip().split()))
        for nodes in nodes_ll:
            ll.append(nodes)  # add to the end of the list

        sortList(ll.head)
        PrintList(ll.head)
        print()
g6baxovj

g6baxovj1#

如果您希望您的方法有效,您只需要将方法的返回行更改为 ll.head = ll1.head .
但是,不应将链表转换为python列表。这里我将给您一个代码,它将使用o(n^2)方法对链表进行排序,每次取最小值,交换并最终在列表的其余部分调用递归,如果您需要更快的速度,可以尝试快速排序。

def sortList(head):

    if not head.next:
        return head

    min = head
    ite = head
    while ite.next:
        ite = ite.next
        if ite.data < min.data:
            min = ite
    head.data, min.data = min.data, head.data
    sortList(head.next)

相关问题