我试图从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__'
答案 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)