2016-09-23 51 views
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和努力得到這個工作,有什麼建議?

+1

不要重新發明輪子,看看[Python的鏈表的問題(HTTP ://stackoverflow.com/questions/280243/python-linked-list),它更清潔。 –

+0

請注意,根據您的使用情況(如果有的話),使用[python的'deque'](https://docs.python.org/3/library/collections.html#collections.deque)可能更多實際 - 它們[以鏈接列表的形式實現](http://stackoverflow.com/a/6257048/5349916)。 – MisterMiyagi

回答

1

雖然你發佈代碼和錯誤行不太匹配,這個問題很可能在這裏:

if data > current_node.data and data <= current_node.next.data: 

當你檢查current_nodeNone,你從來沒有檢查current_node.nextNone無論是。

還有一些其他的錯誤,例如, last_node沒有定義,沒有插入正面的概念,並且您始終瀏覽整個列表。這應該更好的工作:

def insertNode(data, first_node): 
    current_node = first_node 
    new_node = Node(data, current_node.next) 
    if data <= current_node.data: 
    # insert at start 
    first_node = new_node 
    new_node.next = first_node 
    else: 
    while current_node is not None: 
     if current_node.next is None: 
     # insert at end 
     current_node.next = new_node 
     break 
     elif data > current_node.data and data <= current_node.next.data: 
     # insert in-between current and next node 
     new_node.next = current_node.next 
     current_node.next = new_node 
     break 
     current_node = current_node.next 
    print("Inserting node: " + str(data)) 
    return first_node # must return first to avoid global variable! 

爲了支持不斷變化的first_node,你必須填寫列表如下:

rand_num_iter = iter(random_nums) # avoids making a copy in [1:] 
first_node = Node(next(rand_num_iter), None) 
for i in rand_num_iter: 
    first_node = insertNode(i, first_node)