实验题目:删除单链表中最大值结点并返回值
时间: 2024-06-13 13:06:57 浏览: 115
1.单链表的定义.md
以下是实现删除单链表中最大值结点并返回值的Python代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def readlist():
head = ListNode()
tail = head
num_list = input().split()
for num in num_list:
tail.next = ListNode(int(num))
tail = tail.next
return head.next
def printlist(head):
while head:
print(head.val, end=' ')
head = head.next
print()
def deletem(head):
max_val = float('-inf')
cur = head
while cur:
max_val = max(max_val, cur.val)
cur = cur.next
dummy = ListNode(0, head)
pre, cur = dummy, head
while cur:
if cur.val == max_val:
pre.next = cur.next
break
pre, cur = cur, cur.next
return max_val
if __name__ == '__main__':
head = readlist()
max_val = deletem(head)
print(max_val)
printlist(head)
```
输入格式为一行数字,每个数字之间用空格隔开。程序首先通过 `readlist()` 函数将输入的数据存储到链表中,然后通过 `deletem()` 函数找到链表中的最大值并删除该结点,最后通过 `printlist()` 函数输出最终的链表结果。程序输出两行,第一行为删除的最大值,第二行为删除最大值后的链表。
阅读全文