繁体   English   中英

AttributeError: 'NoneType' object 没有属性 'next' 和 Function 缺少 2 个必需的位置 arguments: 'x' 和 'y'

[英]AttributeError: 'NoneType' object has no attribute 'next' and Function missing 2 required positional arguments: 'x' and 'y'

我正在尝试编写一个程序来在特定的 position 插入一个节点,我得到的错误是,

AttributeError: 'NoneType' object has no attribute 'next'

并且

Function missing 2 required positional arguments: 'x' and 'y'

代码:

class SinglyLinkedListNode:
    def __init__(self, data):
        self.data = data
        self.next = None


class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insertnode_end(self, data):
        node = SinglyLinkedListNode(data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node

        self.tail = node

    def print_ll(self):

        temp = self.head
        while temp is not None:
            print(temp.data, end=" ")
            temp = temp.next

    def insertNode_pos(self, data, pos):
        new_node = SinglyLinkedListNode(data)
        if (pos == 0):
            new_node.next = self.head
            self.head = new_node

        temp = self.head
        while temp.next is not None:
            for _ in range(pos - 1):
                temp = temp.next
            new_node.next = temp.next
            temp.next = new_node


llist_count = int(input())
llist = SinglyLinkedList()

for _ in range(llist_count):
    llist_item = int(input())
    llist.insertnode_end(llist_item)

data = int(input())
pos = int(input())

llist.insertNode_pos(data, pos)

llist.print_ll()

我在您的代码中没有看到 x 和 y 。 如果您包含完整的回溯,这将很有帮助。 似乎您的 function 正在命中列表中的最后一个节点,其next一项是无。 显然, None没有nextdata属性。

同时,我修改了您的 insertNode_pos function。 这里重要的一行是return if pos == 0 在这种情况下,您的 function 不需要继续。

 def insertNode_pos(self, data, pos):
    new_node = SinglyLinkedListNode(data)
    if pos == 0:
        new_node.next = self.head
        self.head = new_node
        return

    temp = self.head
    for iter in range(pos):
        if iter == 0:
            temp = self.head
        else:
            temp = temp.next
    new_node.next = temp.next
    temp.next = new_node

还有一点需要注意的是,实现__str__是打印数据内容的一种更常见的做法:

def __str__(self):
    output = []
    temp = self.head
    while temp is not None:
        output.append(str(temp.data))
        temp = temp.next
    return ",".join(output)

然后你可以简单地说print(llist)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM