产生20个1-200的随机整数,并依次保存到带头结点的单链表中,计算单链表的长度,并将结果存放在节点的数据域中,然后输出单链表,从单链表中删除与给定值为x相等的所有节点,然后输出单链表
时间: 2024-10-09 15:05:33 浏览: 38
首先,我们需要创建一个链表结构,每个节点包含一个整数数据和指向下一个节点的指针。在这个过程中,我们将生成20个随机数并将其插入链表。
```python
import random
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_random(self, n=20):
for _ in range(n):
new_num = random.randint(1, 200)
if not self.head:
self.head = Node(new_num)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(new_num)
def calculate_length(self):
length = 0
current = self.head
while current:
length += 1
current = current.next
return length
def print_list(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
def delete_nodes_with_value(self, x):
if not self.head:
return
current = self.head
prev = None
while current and current.data != x:
prev = current
current = current.next
if current is not None:
if prev is None:
self.head = current.next
else:
prev.next = current.next
else:
# 如果链表中没有值为x的节点,则无需处理
def print_deleted_list(self):
self.print_list()
# 示例操作
linked_list = LinkedList()
linked_list.insert_random()
length = linked_list.calculate_length()
print(f"原始链表长度: {length}")
linked_list.delete_nodes_with_value(50) # 删除值为50的节点
linked_list.print_deleted_list()
```
阅读全文