递归是处理链表的绝佳选择,因为链表是递归数据结构。递归允许我们的程序结构与我们的数据结构相匹配 -
# linked_list.py
empty = None
class node:
def __init__(self, value, next = None):
self.value = value
self.next = next
def to_str(t = empty):
if not t:
return "None"
else:
return f"{t.value} -> {to_str(t.next)}"
def middle(t = empty):
def loop(t, ff):
if not t:
return None
elif ff and ff.next:
return loop(t.next, ff.next.next)
else:
return t.value
return loop(t, t)
让我们从我们的基本构建块中获得一些输出 -
# main.py
from linked_list import node, to_str, middle
t1 = node(1, node(2, node(3)))
t2 = node(1, node(2, node(3, node(4))))
t3 = node(1, node(2, node(3, node(4, node(5)))))
print(to_str(t1)) # 1 -> 2 -> 3 -> None
print(to_str(t2)) # 1 -> 2 -> 3 -> 4 -> None
print(to_str(t3)) # 1 -> 2 -> 3 -> 4 -> 5 -> None
print(middle(t1)) # => 2
print(middle(t2)) # => 3
print(middle(t3)) # => 3
将功能模块包裹在 class 中会让人感觉更像 Python -
# linked_list.py
empty = # ...
class node # ...
def to_str # ...
def middle # ...
def from_list(l = []):
if not l:
return empty
else:
return node(l[0], from_list(l[1:]))
class linked_list:
def __init__(self, root = None):
self.root = root
def __str__(self):
return to_str(self.root)
def middle(self):
return middle(self.root)
def from_list(l = []):
return linked_list(from_list(l))
现在我们获得了函数式模块的所有好处以及 oop 式接口的便利 -
from linked_list import linked_list
t1 = linked_list.from_list([1, 2, 3])
t2 = linked_list.from_list([1, 2, 3, 4])
t3 = linked_list.from_list([1, 2, 3, 4, 5])
print(t1) # 1 -> 2 -> 3 -> None
print(t2) # 1 -> 2 -> 3 -> 4 -> None
print(t3) # 1 -> 2 -> 3 -> 4 -> 5 -> None
print(t1.middle()) # => 2
print(t2.middle()) # => 3
print(t3.middle()) # => 3