【发布时间】:2012-02-17 00:09:32
【问题描述】:
我试图在不复制列表节点中包含的数据的情况下连接 Python 链表。我有一个函数将使用传入的节点的副本连接列表,但我似乎无法获得不使用副本工作的函数。
这些函数用于测试和计时目的;我知道 Python 的内置列表很棒!
这是我一直在使用的类和连接函数。
class Cell:
def __init__( self, data, next = None ):
self.data = data
self.next = next
def print_list(self):
node = self
while node != None:
print node.data
node = node.next
连接函数并不意味着是 Cell 类的成员函数。
def list_concat(A, B):
while A.next != None:
A = A.next
A.next = B
return A
如果参数 A 有多个节点,此函数将覆盖列表的第一个元素。我明白为什么会这样,但不知道如何解决它。
这是我一直用于此功能的测试代码。
e = Cell(5)
test = Cell(3, Cell(4))
test2 = list_concat(test2, e)
test2.print_list()
任何见解或帮助将不胜感激。
*已编辑以修复代码格式
【问题讨论】:
-
您的串联功能应该可以工作。请注意,
list不是链表。我建议您查看 lisp 实现,因为它们使用与您相同结构的单元。 -
我认为这个实现应该也可以工作,但是当我打印列表 (test2) 时,它会将元素列为 4 -> 5 -> None,而它应该列出 3 -> 4 -> 5 -> 无。
-
请注意,在您的代码示例中,您使用 test2 作为参数,然后再分配给它。
-
这值得做作业标签吗?
标签: python algorithm linked-list