使用链接列表无法获得正确的打印输出

时间:2016-10-21 11:09:31

标签: python list linked-list nodes

这是我正在使用的功能。它是一个使用nodes类的链表。这是implementation of it from my textbook。但是当我尝试打印时,我得到了这个输出。

< main .Node对象位于0x000001C1A21E5470> < main .Node对象位于0x000001C1A21E5438> < main .Node对象位于0x000001C1A21E54A8> < main .Node对象位于0x000001C1A21E5400>

我读到使用__repr__可以帮助打印,但是当我实现它时它对我不起作用。

def copyList(self):
    links = LinkedList()
    current = self.head
    while current.getNext() != None:
        links.addLast(current)
        current= current.getNext()
    links.addLast(current.getData())
    return links

该函数就像这样调用

list2=list1.copyList()
print(list2)

我尝试的 repr 功能

def __repr__(self):
    string=''
    current = self.head
    if current != None:
        string += str(current.getData())
        current = current.getNext()
        counter=2
        while current:
            string += " "+str(current.getData())
            current = current.getNext()
            if counter>9:
                string=string+'\n'
                counter=0
            counter=counter+1
    return string

1 个答案:

答案 0 :(得分:0)

我似乎误解了你的问题。

我认为问题出在你的copyList函数中。它应该是:

def copyList(self):
    links = LinkedList()
    current = self.head
    while current.getNext() != None:
        links.addLast(current.getData())
        current = current.getNext()
    links.addLast(current.getData())
    return links

您使用了links.addLast(current)。需要查看addLast()方法的实现以获取更多详细信息。

相关问题