以单链表为例,设计一个主程序完成如下功能: 1)初始化单链表L 2) 对L依次插入元素5,34,2,16,22,100 3)依次输出L中的元素 4)求出L中值最大和值最小的元素 5)删除L中第2个结点
时间: 2024-09-27 07:14:59 浏览: 38
首先,为了实现这个功能,我们可以创建一个简单的单链表结构,包含节点数据和指向下一个节点的指针。然后我们可以按照需求逐步实现每个功能:
```python
class ListNode:
def __init__(self, value=0):
self.value = value
self.next = None
# 初始化单链表 L
def create_list():
head = ListNode()
current = head
for num in [5, 34, 2, 16, 22, 100]:
new_node = ListNode(num)
current.next = new_node
current = new_node
return head
# 插入元素到链表
def insert_element(head, value):
new_node = ListNode(value)
if not head:
head = new_node
else:
current = head
while current.next:
current = current.next
current.next = new_node
return head
# 输出链表元素
def print_list(head):
current = head
while current:
print(current.value, end=" -> ")
current = current.next
print("None") # 结束标记
# 找出最大值和最小值
def find_min_max(head):
if not head or not head.next:
return (head.value, head.value)
min_val = max_val = head.value
current = head.next
while current:
if current.value < min_val:
min_val = current.value
elif current.value > max_val:
max_val = current.value
current = current.next
return min_val, max_val
# 删除指定位置的节点
def delete_node(head, position):
if not head or position == 0:
return head
current = head
for _ in range(position - 1):
if not current.next:
raise IndexError("Index out of range")
current = current.next
if not current.next:
return head
current.next = current.next.next
return head
# 主程序
if __name__ == "__main__":
# 1) 初始化单链表L
list_head = create_list()
# 2) 插入元素
list_head = insert_element(list_head, 10)
# 3) 输出链表元素
print("List elements:")
print_list(list_head)
# 4) 求出最大值和最小值
min_value, max_value = find_min_max(list_head)
print(f"Min value: {min_value}, Max value: {max_value}")
# 5) 删除第2个节点
list_head = delete_node(list_head, 1)
# 再次输出链表元素(现在第2个节点已被删除)
print("\nList elements after deleting node at position 2:")
print_list(list_head)
```
阅读全文