Python 属性错误:';非类型';对象没有属性';数据';-当我';我写了一个函数,将一个元素插入到排序链表中
我正在编写一个函数来实现插入到排序的单链表中Python 属性错误:';非类型';对象没有属性';数据';-当我';我写了一个函数,将一个元素插入到排序链表中,python,sorting,data-structures,linked-list,Python,Sorting,Data Structures,Linked List,我正在编写一个函数来实现插入到排序的单链表中 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:
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)
我甚至猜不出代码有什么问题。
我试图用print(currentNode.data)
打印节点数据,但它没有显示错误,只是在条件检查期间出现错误
while True:
currentData = currentNode.data # line with error
if currentData <= newNode.data:
currentPosition += 1
currentNode = currentNode.next
self.insertAt(newNode, currentPosition)
这个循环在InsertAt函数中,您需要知道所提到的位置是否正确。假设职位总数为25个,输入的职位为30个。现在你的循环将失败,因为它永远不会达到30。因此,您需要在while条件中添加一个退出循环,并说明:
while ((currentPosition is not position) and (currentNode is not None))
现在,代码将永远不会失败。您无需猜测,堆栈跟踪将指向精确的行。您永远不会退出该循环。最终
currentNode。下一步
将变为None
,然后将该None
存储在currentNode
中。您需要检查currentPosition
是否为所需值,并检查节点是否为None
(链接列表的末尾)
while currentPosition is not position:
currentPosition += 1
previousNode = currentNode
currentNode = currentNode.next
newNode.next = currentNode
previousNode.next = newNode
while ((currentPosition is not position) and (currentNode is not None))