用Python随便生成一段尾插法的代码
时间: 2023-12-25 18:58:21 浏览: 62
这里是一个简单的尾插法示例:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
curr_node = self.head
while curr_node.next:
curr_node = curr_node.next
curr_node.next = new_node
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next
# Example Usage
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.print_list()
```
运行结果:
```
1
2
3
```
阅读全文