AttributeError: у объекта 'NoneType' нет атрибута 'data' - когда я пишу функцию для вставки элемента в отсортированный связанный список - PullRequest
0 голосов
/ 16 февраля 2020

Я пишу функцию для реализации вставки в отсортированный односвязный список.

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

class LinkedList:
    def __init__(self):
        self.head = None

    def isListEmpty(self):
        if self.head is None:
            return True
        return False

    def listLength(self):
        length = 0
        currentNode = self.head
        while currentNode is not None:
            length += 1
            currentNode = currentNode.next
        return length

    def insertAt(self, newNode, position):
        if position < 0 or position > self.listLength():
            print("Invalid Position")
            return
        elif position == 0:
            self.insertHead(newNode)
        else:
            currentPosition = 0
            currentNode = self.head
            while currentPosition is not position:
                currentPosition += 1
                previousNode = currentNode
                currentNode = currentNode.next
            newNode.next = currentNode
            previousNode.next = newNode

    def insertSort(self, newNode):
        if self.isListEmpty():
            self.insertEnd(newNode)
        else:
            currentPosition = 0
            currentNode = self.head
            while True:
                currentData = currentNode.data  # line with error
                if currentData <= newNode.data:
                    currentPosition += 1
                    currentNode = currentNode.next
            self.insertAt(newNode, currentPosition)

firstNode = Node(10)
link = LinkedList()
link.insertEnd(firstNode)
fifthNode = Node(25)
link.insertSort(fifthNode)

В настоящее время получаю сообщение об ошибке:

     currentData = currentNode.data
AttributeError: 'NoneType' object has no attribute 'data'

Я даже не могу догадаться, что это проблема с кодом. Я попытался напечатать данные узла с помощью print(currentNode.data), но он не показывает ошибок, он появляется только во время проверки состояния.

1 Ответ

1 голос
/ 19 февраля 2020
while True:
currentData = currentNode.data  # line with error
if currentData <= newNode.data:
    currentPosition += 1
    currentNode = currentNode.next
self.insertAt(newNode, currentPosition)

Здесь вы никогда не выходили, пока l oop. Итак, последний currentNode будет содержать None. Проверьте, достигли ли вы конца LinkedList и выйдите.

Я хотел бы добавить еще одну вещь.

while currentPosition is not position:
            currentPosition += 1
            previousNode = currentNode
            currentNode = currentNode.next
        newNode.next = currentNode
        previousNode.next = newNode

Этот l oop в функции InsertAt, вам нужно знать, указанная позиция правильная или нет. Допустим, общее количество позиций было 25, а введенная позиция была 30. Теперь ваш l oop потерпит неудачу, поскольку он никогда не достигнет 30. Поэтому вам нужно добавить один выход l oop, в то время как само условие говорит:

while ((currentPosition is not position) and (currentNode is not None))

Теперь код никогда не потерпит неудачу.

...