python使用降序列表a=[99,89,79,69,59]中的数据创建一个单向循环链表b 在链表b中插入一个数n,使得链表b仍旧非升序
时间: 2023-05-28 22:05:57 浏览: 109
探讨:将两个链表非降序合并为一个链表并依然有序的实现方法
下面是一种可能的实现方式:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
a = [99, 89, 79, 69, 59]
# 创建单向循环链表b
head = Node(a[0])
curr = head
for i in range(1, len(a)):
node = Node(a[i])
curr.next = node
curr = node
curr.next = head
# 插入新节点n
n = 75
node = Node(n)
if n >= head.data:
# 如果n比头节点还大,直接插入到头节点之前
curr = head
while curr.next != head:
curr = curr.next
curr.next = node
node.next = head
head = node
else:
# 否则找到第一个比n小的节点,插入在它之后
curr = head
while curr.next != head and curr.next.data >= n:
curr = curr.next
node.next = curr.next
curr.next = node
# 打印链表
curr = head
while True:
print(curr.data, end=' ')
curr = curr.next
if curr == head:
break
```
输出:
```
99 89 79 75 69 59
```
阅读全文