连接Python链接列表

Chr*_*asa 4 python algorithm linked-list

我试图连接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
Run Code Online (Sandbox Code Playgroud)

连接函数并不意味着是Cell类的成员函数.

def list_concat(A, B):
    while A.next != None:
        A = A.next
    A.next = B      
    return A
Run Code Online (Sandbox Code Playgroud)

如果参数A具有多个节点,则此函数将覆盖列表的第一个元素.我理解为什么会发生这种情况,但我不确定如何解决这个问题.

这是我一直用于此功能的测试代码.

e = Cell(5)
test = Cell(3, Cell(4))
test2 = list_concat(test2, e)   
test2.print_list()
Run Code Online (Sandbox Code Playgroud)

任何见解或帮助将不胜感激.

*编辑以修复代码格式

Ósc*_*pez 5

试试这个:

def list_concat(A, B):
    current = A
    while current.next != None:
        current = current.next
    current.next = B
    return A
Run Code Online (Sandbox Code Playgroud)

为函数的参数赋值是一个糟糕的编程习惯,问题中的代码说明了原因:您用于A迭代原始列表,并且通过这样做,您丢失了对其第一个元素的引用.