0
當前的代碼,我試圖做一個鏈表,然後按升序對鏈表進行排序。AttributeError:'NoneType'對象沒有屬性'data'鏈接列表
import random
random_nums = random.sample(range(100), 10)
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
def insertNode(data, first_node):
current_node = first_node
while current_node !=None:
if data > current_node.data and data <= current_node.next.data:
new_node = Node(data, current_node.next)
last_node.next = new_node
print("Inserting node: " + str(data))
current_node = current_node.next
first_node = Node(random_nums[0], None)
for i in random_nums[1:]:
insertNode(i, first_node)
print("Linked list values:")
current_node = first_node
while current_node != None:
print (str(current_node.data) + " => ", end="")
current_node = current_node.next
input()
目前得到的錯誤
File "python", line 25, in File "python", line 16, in insertNode AttributeError: 'NoneType' object has no attribute 'data'
我真的很新的Python和努力得到這個工作,有什麼建議?
不要重新發明輪子,看看[Python的鏈表的問題(HTTP ://stackoverflow.com/questions/280243/python-linked-list),它更清潔。 –
請注意,根據您的使用情況(如果有的話),使用[python的'deque'](https://docs.python.org/3/library/collections.html#collections.deque)可能更多實際 - 它們[以鏈接列表的形式實現](http://stackoverflow.com/a/6257048/5349916)。 – MisterMiyagi