链接列表排序错误

时间:2016-11-22 19:12:57

标签: python linked-list bubble-sort

这段代码应该通过一个包含6个元素的列表进行排序,忽略第一个元素。出于某种原因,我总是得到一个错误,指出“TypeError:'NoneType'对象不可订阅”。如果有人能给我一个解决方案或向我解释一个非常感谢的解决方案。

def bubbleSortLinkedList(aLinkedList):
    pointer = aLinkedList
    swapped = True
    while swapped:
        pointer = aLinkedList['next']
        swapped = False
        for i in range(4):
            if pointer['data'] > pointer['next']['data']:
                pointer['data'], pointer['next']['data'] = pointer['next']['data'], pointer['data']
                swapped = True
            pointer = pointer['next']
        aLinkedList = pointer 
    return aLinkedList

1 个答案:

答案 0 :(得分:0)

在while循环的最后一行中,您编写了aLinkedList = pointer,它将列表指向最后一个元素。但是,您打算将指针设置为列表的第一个元素。

这是更正后的代码:

def bubbleSortLinkedList(aLinkedList):
    pointer = aLinkedList
    swapped = True
    while swapped:
       pointer = aLinkedList['next']
       swapped = False
       for i in range(4):
           if pointer['data'] > pointer['next']['data']:
               pointer['data'], pointer['next']['data'] = pointer['next']['data'], pointer['data']
               swapped = True
            pointer = pointer['next']

        pointer = aLinkedList # This line was wrong!!!!! 

    return aLinkedList