# 如何将节点添加到链表？

2022-11-24 15:23:52

ll = converts_list_to_linked_list([4, 7, 9, 14]) #我有一个链表：4->7->9->12->14

insert_ordered(ll, 12)

def insert_ordered(ll,x):

new_node = LN(v) #Creates new node

#If given ll is empty, newnode is the linkedlist

if  ll == None:

ll = new_node

#Makes new_node the head of ll if first val is >= new_node value.

elif ll.value >= new_node.value:

temp = ll

ll = new_node

ll.next = temp

#[ERROR] Adds new_node between two nodes of ll in sorted order.

else:

while ll.next != None:

if ll.value < new_node.value:

ll = ll.next

new_node.next = ll.next

ll.next = new_node

return ll

## 1 回答

SMILET

TA贡献1485条经验 获得超4个赞

class LN:

def __init__(self, value):

self.value = value

self.next = None

def insert_ordered(root, data):

node = LN(data)

if root == None:

return node

else:

if root.value > data:

node.next = root

return node

else:

temp, prev = root, None

while temp.next and temp.value <= data:

prev = temp

temp = temp.next

if temp.next == None and temp.value <= data:

temp.next = node

else:

node.next = prev.next

prev.next = node

return root

root = None

root = insert_ordered(root, 4)

root = insert_ordered(root, 7)

root = insert_ordered(root, 9)

root = insert_ordered(root, 14)

root = insert_ordered(root, 12)

#4->7->9->12->14

• 1 回答
• 0 关注
• 7 浏览

0/150