单链表可通过实现__iter__和__next__方法支持Python迭代协议;需定义独立迭代器类封装遍历逻辑,使链表支持for循环、next()调用、解包及内置函数如list()和sum(),且不修改原结构。

单链表本身不自带迭代器,但可以手动实现一个迭代器类,使其支持 for 循环、next() 调用等 Python 迭代协议(即实现 __iter__ 和 __next__ 方法)。
定义单链表节点和链表结构
先构建基础的单链表,便于后续为其添加迭代能力:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
<p>class LinkedList:
def <strong>init</strong>(self):
self.head = None</p><pre class="brush:php;toolbar:false;">def append(self, val):
new_node = ListNode(val)
if not self.head:
self.head = new_node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node为链表实现可迭代接口
在 LinkedList 类中添加 __iter__ 方法,返回一个迭代器对象。推荐将迭代器逻辑封装为独立类,更清晰且支持多次遍历:
class LinkedListIterator:
def __init__(self, head):
self.current = head
<pre class="brush:php;toolbar:false;">def __iter__(self):
return self
def __next__(self):
if self.current is None:
raise StopIteration
value = self.current.val
self.current = self.current.next
return value在 LinkedList 类中添加:
def __iter__(self):
return LinkedListIterator(self.head)- 每次调用
iter(linked_list)都会创建新迭代器,因此可重复遍历 - 迭代器状态保存在
self.current中,不污染原链表 - 符合 Python 迭代器协议,能直接用于
for x in linked_list:
实际使用示例
构造链表并遍历:
ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) <p>for val in ll: print(val) # 输出:1 2 3</p><h1>也可手动控制:</h1><p>it = iter(ll) print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3 print(next(it)) # StopIteration 异常 </p>
- 支持解包:
a, b, c = ll(需元素个数匹配) - 兼容内置函数:
list(ll)→[1, 2, 3],sum(ll)→6 - 不会修改原链表结构,安全可靠
进阶:支持反向迭代(可选)
若需从尾到头遍历,可在链表中增加 __reversed__ 方法,或借助辅助栈/递归收集节点值后返回反向迭代器。但注意:单链表天然不支持 O(1) 反向访问,所以反向迭代通常是 O(n) 时间 + O(n) 空间。
- 简单实现(基于列表暂存):
def __reversed__(self): return reversed(list(self)) - 更省内存的做法是先统计长度,再用双指针或递归回调,但复杂度更高,一般按需选用











