AttributeError: 'NoneType'对象没有属性'next',Function缺少2个必要的位置参数。'x'和'y'。

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

我试图写一个程序在特定的位置插入一个节点,我得到的错误是。

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()
python linked-list
1个回答
0
投票

我在你的代码中没有看到x和y。如果你能提供完整的回溯,那会很有帮助。看起来你的函数是在打列表中的最后一个节点,它的 next 项为无。显然,。None 没有 nextdata 属性。

同时,我修改了你的insertNode_pos函数。其中重要的一行是 return 如果 pos == 0. 在这种情况下,你的函数不需要继续。

 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)

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