[英]How to get node for negative index in a linked list?
嗨,我是Python的初學者,我才剛剛開始學習鏈表。 我寫了一個方法get node,使節點位於列表中的特定索引處,但現在我想嘗試從負索引中獲取節點。 例如,如果a_list = [1,2,3],a_list [-1]將等於3,依此類推。 這是我的get_node方法,僅適用於正索引:
def _get_node(self, index):
if index >0 and index >=len(self) :
raise IndexError( "Positive index out of range")
node=self.head
for _ in range(index):
node=node.next
return node
現在,我嘗試為負索引編寫另一種方法:
def _get_nodeNegative(self, index):
if index <0 and index < -1 *len(self) :
raise IndexError( "Positive index out of range")
if index==-1:
node=self._get_node(len(self)-1)
else:
for _ in range(index, 0 ,1):
//Problem here
node=node.next
return node
問題是鏈表只能向前迭代,因此如果我嘗試獲取a_list [-2],則會收到錯誤AttributeError:'NoneType'對象沒有屬性'next'。
任何的意見都將會有幫助。
你寫了
node=node.next
但是沒有定義“節點”對象,因此它是“ NoneType”對象。 定義它的唯一時間是在它上面的if語句中,但實際上,如果您進入else語句,則尚未創建執行node.next的節點對象。
負索引和正索引之間的關系是正索引-len(self)=負索引,因此我在getNodeNegative中需要更改的所有內容是
for _ in range(index, 0 ,1):
node=self._get_node(index+len(self))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.