【问题描述】创建一个单链表,并求其最大值。 【输入形式】从键盘输入若干个整数,以空格分开,-1作为输入结束。 【输出形式】如果存在最大值,则输出;否则输出No answer! 【样例输入】65 12 6 78 5 -1 【样例输出】78
时间: 2023-12-04 12:03:38 浏览: 109
以下是 Python 的实现代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 从数组创建单链表
def createLinkedList(nums):
if not nums:
return None
head = ListNode(nums[0])
cur = head
for i in range(1, len(nums)):
node = ListNode(nums[i])
cur.next = node
cur = cur.next
return head
# 求单链表的最大值
def getMaxValue(head):
if not head:
return "No answer!"
max_val = head.val
cur = head.next
while cur:
if cur.val > max_val:
max_val = cur.val
cur = cur.next
return max_val
# 从键盘输入若干个整数,以空格分开,-1作为输入结束
nums = list(map(int, input().split()))
head = createLinkedList(nums)
print(getMaxValue(head))
```
输入样例:65 12 6 78 5 -1
输出样例:78
阅读全文
相关推荐










