Python数据结构问题next_node类型问题?

问题描述 投票:0回答:1

我想将数据设置到我的链接列表中。但我的代码有什么问题?如何添加新的链接列表?

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next_node = next_node


class LinkedList:
    def __init__(self, head_node=None):
        self.head_node = Node(head_node)

    def add_new_head(self, new_head_node):
        # --------> what line of code goes here?
        
        self.head_node = new_head_node
        new_head_node.next_node = self.head_node
li= LinkedList(4)
li.add_new_head(5)
li.add_new_head(6)
print(li)
python data-structures
1个回答
0
投票

有一些问题:

  • 参数

    head_node
    new_head_node
    的名称具有误导性:正如其名称所示,它们并不是
    Node
    的实例,而是用于 创建 节点的 (整数)。所以也许可以称他们为
    head_value
    new_head_value

    可能是由于这种错误命名,您会这样做

    self.head_node = new_head_node
    ,但这会将整数分配给应该是节点引用的属性。在
    __init__
    方法中,您做得正确,首先创建了一个 Node,然后将 that 分配给
    self.head_node
    。同样的事情也应该发生在
    add_new_head

  • 赋值

    new_head_node.next_node = self.head_node
    来得太晚了:到那时
    self.head_node
    已经等于
    new_head_node
    ,因此(如果之前的错误已更正),这将创建循环引用。

  • 不是问题,但是由于您的

    Node
    构造函数允许为 next 节点提供可选参数,因此您可以在
    add_new_head
    中使用它,使代码相当优雅。

  • 您的

    LinkedList
    构造函数 always 创建一个节点。这是不对的,因为这样你就不能创建一个“空”链接列表。我不太清楚为什么要向这个构造函数传递一个值。要么没有此参数,要么允许将多个值作为参数传递。没有理由需要这个构造函数来允许 one 值。

    print(li)
  • 不会显示有用的内容。要获得一些可读的输出,请实现
  • __repl__

    方法,以便它将列表作为字符串返回(可以使用

    print
    打印)
    
    
    class Node:
        def __init__(self, value, next_node=None):
            self.value = value
            self.next_node = next_node
    
    
    class LinkedList:
        def __init__(self):  # No extra parameter: just create an empty linked list
            self.head_node = None
    
        def add_new_head(self, new_head_value):  # argument is a value
            # Create node with Node constructor, and use second argument to link it
            self.head_node = Node(new_head_value, self.head_node)  
    
        def __iter__(self):  
            node = self.head_node
            while node:
                yield node.value
                node = node.next_node
                
        def __repr__(self):
            return " ".join(map(repr, self))  # This uses __iter__
    
    li = LinkedList()  # No arguments here. Use `add_new_head` for adding values
    li.add_new_head(4)
    li.add_new_head(5)
    li.add_new_head(6)
    print(li)
    

© www.soinside.com 2019 - 2024. All rights reserved.