Frage

I am trying to get the second to last element from a singly linked list in python. Here is my implementation:

class ListNode:
    def __init__(self, data, next):
        self.data = data
        self.next = next

def make_arr(xx, arr):
    if xx == None:
        return arr
    else:
        arr.insert(0, xx.data)
        make_arr(xx.next, arr)

When I do the following:

lst = ListNode(1, ListNode(2, ListNode(3, ListNode(3, None))))
print make_arr(lst, [])[2]

I get the error:

'NoneType' object has no attribute '__getitem__'
War es hilfreich?

Lösung

You're not returning arr in make_arr...

Edit: a version of your code that works

def make_arr(xx, arr):
    if xx == None:
        return arr

    # No need for the else, in this case
    arr.insert(0, xx.data)
    return make_arr(xx.next, arr)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top