Python 链表中的有序插入未添加节点
我是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
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