Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 链表中的有序插入未添加节点_Python_Linked List - Fatal编程技术网

Python 链表中的有序插入未添加节点

Python 链表中的有序插入未添加节点,python,linked-list,Python,Linked List,我是Python新手。我试图将有序插入编码到链表中,这样链表就可以保持升序 但是,在我调用my\u linked\u list.as\u order(1) 我做错了什么 def as_order(self,x): new_node=Node(x) if self.head is None or self.head.data < x: n=self.head new_node.next=n n=new_node else

我是Python新手。我试图将有序插入编码到链表中,这样链表就可以保持升序

但是,在我调用
my\u linked\u list.as\u order(1)

我做错了什么

def as_order(self,x):
    new_node=Node(x)
    if self.head is None or self.head.data < x:
        n=self.head
        new_node.next=n
        n=new_node
    else:
        n=self.head
        while(n.next is not None and n.next.data < x):
            n=n.next
        new_node.next=n.next
        n.next=new_node
def as_顺序(self,x):
新节点=节点(x)
如果self.head为None或self.head.data
您的代码中有两个问题:

  • 它从不给self.head赋值,因此无法将节点添加到空列表中,或者添加需要成为列表中第一个节点的节点

  • 解决前一个问题后,将在其前面插入大于头部值的值,这违反了预期顺序

两个错误都位于相同的
if
块中。因此,改变这一点:

if self.head is None or self.head.data < x:
    n=self.head
    new_node.next=n
    n=new_node
if self.head is None or self.head.data >= x:  # corrected comparison
    new_node.next = self.head  # (simplification)
    self.head = new_node  # make new node the head