(1)产生20个1~200的随机整数,并依次保存到带头结点的单链表中。(2)计算单链表的长度,并将结果存放在头结点的数据域中,然后输出单链表的所有元素。(3)从单链表中删除与给定值x相等的所有结点,并输出结果。
时间: 2024-10-14 19:15:27 浏览: 29
小白算法积累——单链表15#2个带头结点单链表+提取公共元素+二表合一
(1)在Python中,你可以使用random库生成随机整数并创建链表。首先,创建一个Node类作为链表节点,然后创建链表类ListNode用于操作。以下是一个示例:
```python
import random
class Node:
def __init__(self, value=0):
self.value = value
self.next = None
class ListNode:
def __init__(self):
self.head = Node()
def append(self, num):
if not self.head.next:
self.head.next = Node(num)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(num)
# 生成随机整数并添加到链表
nums = [random.randint(1, 200) for _ in range(20)]
for num in nums:
linked_list = ListNode()
linked_list.append(num)
```
(2)接下来计算链表长度,并更新头节点的数据域:
```python
def length(head):
count = 0
current = head.next
while current:
count += 1
current = current.next
head.value = count
return count
length(linked_list.head)
# 输出所有元素
current = linked_list.head.next
while current:
print(current.value)
current = current.next
```
(3)最后删除链表中等于给定值x的节点:
```python
def delete_nodes(x, head):
if not head or not head.next:
return head
current = head
while current and current.value != x:
prev = current
current = current.next
if current and current.value == x:
if current == head:
head = head.next
else:
prev.next = current.next
return head
# 删除特定值的节点
delete_nodes(x, linked_list.head)
# 再次输出链表
current = linked_list.head.next
while current:
print(current.value)
current = current.next
```
阅读全文