我正在编写一个函数来实现插入到排序的单链表中。
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)
打印节点数据,但它没有显示错误,它只是在条件检查时出现错误。
while True:
currentData = currentNode.data # line with error
if currentData <= newNode.data:
currentPosition += 1
currentNode = currentNode.next
self.insertAt(newNode, currentPosition)
在这里,您从未退出while循环。因此,最终的currentNode将包含None。检查是否已到达LinkedList的末尾并退出。
我想补充一点。
while currentPosition is not position:
currentPosition += 1
previousNode = currentNode
currentNode = currentNode.next
newNode.next = currentNode
previousNode.next = newNode
InsertAt函数中的这个循环需要知道所提到的位置是否正确。假设职位总数为25个,输入的职位为30个。现在你的循环将失败,因为它永远不会达到30。所以你需要在while条件本身中添加一个退出循环:
while ((currentPosition is not position) and (currentNode is not None))
现在,代码永远不会失败。