输入一个正整数序列,遇负数时停止,建立一个线性链表存储读入的数据,然后从键盘读入一数据x,在该链表中删除比x大的数据后输出
时间: 2024-06-09 13:09:13 浏览: 12
以下是Python的实现代码:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
if not self.head:
self.head = Node(data)
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(data)
def delete_greater(self, x):
curr = self.head
prev = None
while curr:
if curr.data > x:
if prev:
prev.next = curr.next
else:
self.head = curr.next
curr = curr.next
else:
prev = curr
curr = curr.next
def print_list(self):
curr = self.head
while curr:
print(curr.data, end=' ')
curr = curr.next
print()
# 读入输入数据
lst = LinkedList()
while True:
data = int(input())
if data < 0:
break
lst.add_node(data)
# 删除比x大的数据
x = int(input())
lst.delete_greater(x)
# 输出结果
lst.print_list()
```
示例输入:
```
1
2
3
-4
5
6
-1
4
```
输入解释:
输入的正整数序列为:1, 2, 3, 5, 6。
输入的数据x为:4。
示例输出:
```
1 2 3
```
输出解释:
由于链表中只有1, 2, 3, 5, 6这几个数比4小,因此删除比4大的数据后,链表中剩余的数据为1, 2, 3。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)