2、以单链表为例,设计一个主程序完成如下功能: 1)初始化单链表L 2)对L依次插入元素5,34,2,16,22,100 3)依次输出L中的元素 4)求出L中值最大和值最小的元素 5)删除L中第2个结点
时间: 2024-10-12 18:05:31 浏览: 27
guofu11111111111111.rar_单链表_单链表 c语言_线性链表程序
在Python中,我们可以创建一个简单的单链表节点类以及相关的操作函数来实现这个需求。首先,我们需要定义链表节点类`ListNode`:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
```
接下来,我们创建一个链表操作类`ListManager`,包含初始化、插入、遍历、查找最大值最小值以及删除节点等方法:
```python
class ListManager:
def __init__(self):
self.head = None
def init_list(self):
self.head = ListNode()
def insert(self, value):
if not self.head:
self.head = ListNode(value)
else:
current = self.head
while current.next:
current = current.next
current.next = ListNode(value)
def print_list(self):
current = self.head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
def find_max_min(self):
max_val = min_val = self.head.val if self.head else None
current = self.head
while current:
if current.val > max_val:
max_val = current.val
elif current.val < min_val:
min_val = current.val
current = current.next
return max_val, min_val
def delete_node(self, index):
if not self.head or index == 0:
return
if index == 1:
self.head = self.head.next
return
prev = self.head
for _ in range(index - 1):
prev = prev.next
prev.next = prev.next.next
```
现在我们可以在主程序中按照要求执行操作:
```python
# 主程序
list_manager = ListManager()
list_manager.init_list()
for value in [5, 34, 2, 16, 22, 100]:
list_manager.insert(value)
list_manager.print_list()
max_value, min_value = list_manager.find_max_min()
print(f"Max value: {max_value}, Min value: {min_value}")
list_manager.delete_node(2) # 删除第二个节点
list_manager.print_list()
```
运行上述代码,即可完成链表的操作。
阅读全文