试写一算法试写一算法,实现正位序输入 n 个数据元素的值,建立带头结点的单链表,要求时间复杂度是线性阶的,实现正位序输入 n 个数据元素的值,建立带头结点的单链表,要求时间复杂度是线性阶的
时间: 2024-10-25 09:08:52 浏览: 29
倒位序由奇偶分组造成,以N=为例-FFT算法介绍
算法描述(Python示例):
```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 value > current.next.data:
current = current.next
new_node = Node(value)
new_node.next = current.next
current.next = new_node
return head
# 正确顺序输入n个数据
n = int(input("请输入数据元素的数量:"))
head = None # 初始头节点
for i in range(n):
value = int(input(f"请输入第{i+1}个元素:"))
head = insert_sorted(head, value)
# 打印链表 (这里仅显示结构,实际打印需要遍历)
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None") # 结束标记
阅读全文