利用尾插法创建一个8个元素的整型数据的单链表,测试数据输入数据1, 2,3,4,5,6,7,8,输出1,2,3,4,5,6,7,8,
时间: 2024-12-31 11:49:05 浏览: 11
尾插法是一种在单链表的末尾添加新节点的方法。以下是利用Python编写的一个简单示例,创建一个包含给定数据的单链表,并打印出每个节点的值:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def append_to_list(head, value):
if head is None:
head = Node(value)
else:
current = head
while current.next is not None:
current = current.next
current.next = Node(value)
return head
# 初始化链表头部
head = None
# 测试数据
data = [1, 2, 3, 4, 5, 6, 7, 8]
# 使用尾插法添加数据到链表
for num in data:
head = append_to_list(head, num)
# 打印链表的所有节点
current = head
while current is not None:
print(current.data, end=" -> ")
current = current.next
print("None") # 结束节点
阅读全文