输入一批正整数(数据个数未知,以0结束),用单链表存储,输出大于平均值的数。用Python编写
时间: 2024-09-08 13:03:15 浏览: 35
在Python中,你可以通过遍历链表并维护当前元素总和以及计数来解决这个问题。这里是一个基本的步骤:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def sum_and_count(head):
total_sum = 0
count = 0
current = head
while current and current.val != 0:
total_sum += current.val
count += 1
current = current.next
average = total_sum / count if count > 0 else 0 # 防止除数为零错误
larger_than_average = []
current = head
while current:
if current.val > average:
larger_than_average.append(current.val)
current = current.next
return larger_than_average
# 示例:
# 定义链表节点
node1 = ListNode(5)
node2 = ListNode(2)
node3 = ListNode(8)
node4 = ListNode(1)
node5 = ListNode(9) # 0 结束
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
result = sum_and_count(node1)
print("大于平均值的数有:", result)
```
这个函数首先计算出链表中所有数字的总和和个数,然后计算平均值。接着再次遍历链表,将大于平均值的数值添加到结果列表中。
阅读全文