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

问题描述:

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) 

任何人都可以帮忙吗?

+0

不,因为'LinkedList.add()'在开始处添加了一个新节点*。你有没有尝试遍历链接到最后并添加一个新的节点? –

+1

每次换头都不会让你太过分...... –

+1

@ Jean-FrançoisFabre:其实会。但增加到最后是这里的问题。 –

你需要循环的链接列表,并在末尾添加一个新的节点,而不是:

def insert_at_end(linked_list, item): 
    if linked_list.is_empty(): 
     linked_list.add(item) 
    else: 
     node = linked_list.head 
     while node.next is not None: 
      node = node.next 
     node.next = Node(item, None) 

这将重新使用现有的方法在添加一个节点一开始如果链接的列表是空的。

演示:

>>> 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 
+0

Martijn,我早些时候尝试过,但它也没有工作。虽然 – Gabzmann

+0

@Gabzmann:那么你是如何测试的?你没有定义什么*没有工作*在这里意味着,所以我不能帮你进一步。以上无疑是正确的方法。 –

+0

@Gabzmann:如果你a)包括你的其他尝试,b)显示你的输入和预期的输出,并且c)向我们展示发生了什么(包括任何错误),你的问题会大大改善。这就是所谓的[mcve]。 –

一种选择是将__iter__()魔术方法添加到您的LinkedList,使其可迭代:

通过节点
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) 

加上__iter__()魔法也有您可以使用迭代来构建链表的字符串表示形式。通过定义__str__()魔术方法,您可以使用print(my_list)来打印2->3->5之类的东西,如果您定义了__iter__()方法,那么使用列表理解很容易。

请注意,这实际上与the answer given by @MartijnPieters相同,只是它的形式不同。您仍在循环查看列表,直到完成并在最后添加项目。