单链表Python实现

时间:2014-02-09 23:40:42

标签: python singly-linked-list

我试图从python中的单链表中获取倒数第二个元素。这是我的实施:

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)

当我执行以下操作时:

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

我收到错误:

'NoneType' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:2)

您未在arr ...

中返回make_arr

编辑:适用的代码版本

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)