Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
连接Python链表_Python_Algorithm_Linked List - Fatal编程技术网

连接Python链表

连接Python链表,python,algorithm,linked-list,Python,Algorithm,Linked List,我试图连接Python链表,而不复制链表节点中包含的数据。我有一个函数,它将使用传入的节点的副本连接列表,但我似乎无法获得不使用副本的函数 这些功能用于测试和计时目的;我知道Python的内置列表非常棒 这是我一直在使用的类和连接函数 class Cell: def __init__( self, data, next = None ): self.data = data self.next = next def print_list(self):

我试图连接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
e = Cell(5)
test = Cell(3, Cell(4))
test2 = list_concat(test2, e)   
test2.print_list()
连接函数不是Cell类的成员函数

def list_concat(A, B):
    while A.next != None:
        A = A.next
    A.next = B      
    return A
如果参数a有多个节点,此函数将覆盖列表的第一个元素。我理解为什么会发生这种情况,但不知道如何着手解决它

这是我用于此函数的测试代码

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
e = Cell(5)
test = Cell(3, Cell(4))
test2 = list_concat(test2, e)   
test2.print_list()
如有任何见解或帮助,将不胜感激

*编辑以修复代码格式

请尝试以下操作:

def list_concat(A, B):
    current = A
    while current.next != None:
        current = current.next
    current.next = B
    return A

为函数的参数指定新值是一种糟糕的编程实践,您问题中的代码说明了原因:您使用
a
对原始列表进行迭代,这样做会丢失对其第一个元素的引用。

我不确定
extend
是否执行复制,但如果它不执行,只用

A.extend(B)

您的连接函数应该可以工作。请注意,
list
不是链表。我建议您看看lisp实现,因为它们使用与您相同结构的单元格。我认为这个实现也应该可以工作,但是当我打印列表(test2)时,它将元素列为4->5->None,而它应该列为3->4->5->None。请注意,在您的代码示例中,在分配给test2之前,您正在使用它作为参数。这是否值得使用家庭作业标记?另一种可能是将“查找列表末尾”部分分解为一个单独的函数,返回最后一个节点。然后是列表(A,B):查找结束(A);返回一个或者,我很惭愧刚刚想到了他的,不要像Python内置的列表类那样返回列表。对不起,我错过了你说的为了测试而这样做的部分