对任意输入的一组数据,建立一个递增有序的单链表
时间: 2023-05-12 21:03:55 浏览: 57
可以使用插入排序的思想来建立一个递增有序的单链表。具体步骤如下:
1. 创建一个空链表作为结果链表。
2. 遍历输入的数据,对于每个数据,找到它在结果链表中应该插入的位置,并将其插入到该位置。
3. 返回结果链表。
以下是示例代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insert_sorted(head, val):
if not head or head.val > val:
return ListNode(val, head)
p = head
while p.next and p.next.val <= val:
p = p.next
p.next = ListNode(val, p.next)
return head
def build_sorted_list(nums):
head = None
for num in nums:
head = insert_sorted(head, num)
return head
```
其中,`ListNode` 是链表节点的定义,`insert_sorted` 是将一个值插入到有序链表中的函数,`build_sorted_list` 是建立有序链表的函数。可以使用以下代码测试:
```python
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
head = build_sorted_list(nums)
while head:
print(head.val, end=' ')
head = head.next
```
输出结果为:1 1 2 3 3 4 5 5 5 6 9