簡體   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