Python 如何将项目添加到链接列表的末尾?

Python 如何将项目添加到链接列表的末尾?,python,algorithm,python-3.x,linked-list,Python,Algorithm,Python 3.x,Linked List,我试着这样做,但不起作用 class Node: def __init__(self, item, next): self.item = item self.next = next class LinkedList: def __init__(self): self.head = None def add(self, item): self.head = Node(item, self.head)

我试着这样做,但不起作用

class Node:
    def __init__(self, item, next):
        self.item = item
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, item):
        self.head = Node(item, self.head)

    def is_empty(self):
        return self.head == None

有人能帮忙吗?

您需要在链接列表上循环,并在末尾添加一个新节点:

from LinkedList import Node, LinkedList

def insert_at_end(linked_list, item):
    linked_list.add(item)
如果链表为空,则重新使用现有方法在一开始添加节点

演示:


一个选项是将
\uuuu iter\uuuu()
魔术方法添加到您的LinkedList中,以使其可编辑:

>>> def print_ll(ll):  # something to print the list
...     node = ll.head
...     while node is not None:
...         print node.item,
...         node = node.next
...
>>> linked_list = LinkedList()
>>> insert_at_end(linked_list, 10)
>>> insert_at_end(linked_list, 42)
>>> insert_at_end(linked_list, 'foo')
>>> print_ll(linked_list)
10 42 foo
现在,您可以迭代节点以添加到尾部:

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current
            current = current.next
        else:
            raise StopIteration
添加
\uuuu iter\uuuu()
魔术方法还有一个好处,即您可以使用迭代来构造链表的字符串表示形式。通过定义
\u str\u()
魔术方法,您可以使用
打印(我的列表)
打印类似
2->3->5
的内容,如果定义了
\u iter\u()
方法,则很容易理解列表


请注意,这实际上与相同,只是形式不同。您仍然在列表中循环,直到到达末尾并在末尾添加项目。

否,因为
LinkedList.add()
会在开始处添加一个新节点。你有没有尝试过遍历链接到末端,并在那里添加一个新节点?每次替换头部都不会让你走得太远…@Jean-Françoisfare:事实上会的。但最后的问题是,Martijn,我之前试过了,但也没用。谢谢though@Gabzmann:那么你是如何测试的?你没有定义什么是无效的,所以我无法进一步帮助你。以上方法当然是正确的。@Gabzmann:如果你a)包括你的其他尝试,b)显示你的输入和预期输出,c)显示发生了什么(包括任何错误),那么你的问题会有很大改进。这叫做a。添加了apicture@Gabzmann您的代码不完整。将您在屏幕截图中显示的内容与my function的功能进行比较。
    def __iter__(self):
        current = self.head
        while current is not None:
            yield current
            current = current.next
        else:
            raise StopIteration
    def add_tail(self, item):
        if self.is_empty():
            self.add(item)
            return

        # Loop to the end of the list and add the item at the end.
        for node in self:
            pass
        else:
            node.next = Node(item, node.next)