输入n个整数链式存放并输出最大值
时间: 2024-05-03 11:23:03 浏览: 15
这里给出一个示例代码,可以实现输入n个整数链式存放并输出最大值:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def find_max(head):
if not head:
return None
max_val = head.val
curr = head.next
while curr:
if curr.val > max_val:
max_val = curr.val
curr = curr.next
return max_val
n = int(input())
nums = list(map(int, input().split()))
head = ListNode(nums[0])
curr = head
for i in range(1, n):
curr.next = ListNode(nums[i])
curr = curr.next
max_val = find_max(head)
print(max_val)
```
首先定义了一个链表节点类 `ListNode`,包含一个整数值 `val` 和一个指向下一个节点的指针 `next`。然后定义了一个函数 `find_max`,用于在链表中查找最大值,具体实现是遍历链表,维护一个最大值,并不断更新。
在主函数中,先读入整数 `n`,再读入 `n` 个整数,将它们作为链表的节点存储。最后调用 `find_max` 函数查找链表中的最大值,并输出。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)