A. Lewis A. Lewis - 9 days ago 8
Python Question

Linked List sorting error

This code is supposed to sort through a list of 6 elements, ignoring the first. For some reason, I always get an error stating "TypeError: 'NoneType' object is not subscriptable". If anyone could offer me a solution or explain a fix to me that would be much appreciated.

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

Answer

In the last line of the while loop, you have written aLinkedList = pointer, which was pointing the list to the last element. However, what you intended to do was to set the pointer to the first element of the list.

This is the corrected code:

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
Comments