题目描述
构建一个单向链表,链表中包含一组整数数据。输出链表中的所有元素。
要求:
- 使用自定义的链表数据结构
- 提供一个 linkedList 类来管理链表,包含构建链表和输出链表元素的方法
- 在 main 函数中,创建一个包含一组整数数据的链表,然后调用链表的输出方法将所有元素打印出来
输入描述
包含多组测试数据,输入直到文件尾结束。
每组的第一行包含一个整数 n,表示需要构建的链表的长度。
接下来一行包含 n 个整数,表示链表中的元素。
输出描述
每组测试数据输出占一行。
按照顺序打印出链表中的元素,每个元素后面跟一个空格。
输入示例
1 2 3 4
| 5 1 2 3 4 5 6 3 4 5 6 7 8
|
输出示例
提示信息
数据范围:
1 <= n <= 1000;
代码注释
程序结构:
1、链表节点类-存储数据内容和指向下一个节点的指针
2、链表类-管理整个链表,包含插入打印功能
3.、主程序-接受输入,创建链表并操作链表节点类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Node: def __init__(self, data): self.data = data self.next = None
class LinkList: def __init__(self): self.head_node = None self.length = 0 def insert(self, data): self.length += 1 new_node = Node(data) if self.head_node is None: self.head_node = new_node return self.head_node
current_node = self.head_node while current_node.next is not None: current_node = current_node.next
current_node.next = new_node return new_node def print_link_list(self): current_node = self.head_node while current_node is not None: if current_node.next is not None: print(current_node.data, end=' ') else: print(current_node.data) current_node = current_node.next
while True: try: n = int(input()) elements = list(map(int, input().split())) except: break
link_list = LinkList()
for data in elements: link_list.insert(data)
link_list.print_link_list()
|
举个例子
假设我们要定义一个表示汽车的类,每辆汽车有品牌(brand)和速度(speed)这两个属性,并且有一个加速(accelerate)方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Car: def __init__(self, brand, initial_speed): self.brand = brand self.speed = initial_speed
def accelerate(self, increment): self.speed += increment
my_car = Car("Tesla", 0)
print(f"品牌: {my_car.brand}") print(f"当前速度: {my_car.speed}")
my_car.accelerate(30) print(f"加速后的速度: {my_car.speed}")
运行结果: D:\python.exe F:\Pycharm\4.07Linklist.py 品牌: Tesla 当前速度: 0 加速后的速度: 30
|