输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算: 输入一个正整数 n(0<n<=9)和一组(n个)升序的整数,建立单向链表,再输入一个整数 x,把 x 插入到这组数据中,使该组数据仍然有序
时间: 2023-11-04 11:06:05 浏览: 123
以下是 Python 代码实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertNode(head, x):
# 如果链表为空,直接返回插入的节点
if not head:
return ListNode(x)
# 如果插入的值比头结点的值小,插入到头结点前面
if x < head.val:
newNode = ListNode(x)
newNode.next = head
return newNode
# 找到插入位置
curr = head
while curr.next and curr.next.val < x:
curr = curr.next
# 插入节点
newNode = ListNode(x)
newNode.next = curr.next
curr.next = newNode
return head
repeat = int(input("请输入测试次数:"))
for i in range(repeat):
n = int(input("请输入升序整数的个数:"))
nums = list(map(int, input("请输入升序整数:").split()))
x = int(input("请输入要插入的整数:"))
# 构建链表
head = ListNode(nums[0])
for j in range(1, n):
head = insertNode(head, nums[j])
# 插入节点
head = insertNode(head, x)
# 输出结果
while head:
print(head.val, end=" ")
head = head.next
print()
```
输入样例:
```
2
5
1 3 5 7 9
4
3
2 4 6
5
```
输出样例:
```
1 3 4 5 7 9
2 4 5 6
```
阅读全文