我想從python單向鏈表中倒數第二個元素。下面是我的實現:單鏈表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__'
除了你的'None'問題,你正在建立'arr'作爲你的鏈表的反轉版本。這是故意的嗎? –
是的,因爲一旦我將它倒過來......我將能夠檢索倒序列表的第三個元素,它將成爲原始元素的倒數第二個元素。 (線性算法) – user2837048