编写在非递减有序链表中插入一个元素(整型),使链表元素仍有序的函数(必须采用函数实现,否则不算成绩),并利用该函数建立一个非递减有序单向链表,之后输出这个有序的单链表。
时间: 2024-10-10 17:07:07 浏览: 22
在Python中,我们可以创建一个Node类表示链表节点,并编写一个`insert_sorted`函数来插入新的元素保持链表的非递减顺序。这里是一个简单的实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def insert_sorted(head, value):
# 如果链表为空或新值小于当前头节点
if not head or value <= head.data:
new_node = Node(value)
new_node.next = head
return new_node
else:
current = head
while current.next and current.next.data < value:
current = current.next
# 插入新节点到适当位置
new_node = Node(value)
new_node.next = current.next
current.next = new_node
return head
# 创建初始非递减有序链表
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
# 插入新元素5
head = insert_sorted(head, 5)
# 输出链表
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None") # 结束标记
阅读全文