🌟Python实现链表 & 链表输出🌟
在编程的世界里,链表是一种常见的数据结构,它通过节点(Node)的形式存储和管理数据。今天,让我们用Python语言来亲手实现一个简单的链表,并学会如何优雅地输出它的内容!💫
首先,我们需要定义链表的基本单元——节点类`Node`。每个节点包含两部分:存储的数据和指向下一个节点的引用。接着,构建链表的核心逻辑:添加新节点、遍历节点等操作。例如:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
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
last = self.head
while last.next:
last = last.next
last.next = new_node
```
完成链表创建后,我们可以通过循环遍历所有节点并打印它们的内容。比如:
```python
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
```
最后,调用`print_list()`方法即可直观地看到链表中的数据啦!🎉
通过这种方式,不仅能够加深对链表的理解,还能锻炼代码实践能力哦!💪 Python 链表 数据结构