写一个名为myins()的函数,该函数对任意给定的递增有序单链表和整数x,可以将一个值为x的结点插入到该有序单链表中并保持新的单链表有序。
时间: 2023-03-15 12:41:36 浏览: 66
def myins(head, x):
# 创建新结点
new_node = Node(x)
# 临时结点
curr = head
# 如果链表为空,则将新结点设为表头
if head == None:
head = new_node
# 如果 x 比表头结点值小,则将新结点插入到表头
elif x <= head.data:
new_node.next = head
head = new_node
# 在链表中寻找新结点的位置
else:
while curr.next is not None and x > curr.next.data:
curr = curr.next
# 将新结点插入到链表中
new_node.next = curr.next
curr.next = new_node
return head