您的位置:首頁技術文章
文章詳情頁

python鏈表類中獲取元素實例方法

瀏覽:10日期:2022-06-27 11:18:51
1、append方法

向鏈表添加元素后。在鏈表中,不能通過索引來定位每個元素,只能在列表中定位。鏈表元素的.next方法需要被持續調用,以獲得下一個元素,并最終獲得最后一個元素。最后一個元素的.next屬性中將指向新添加的元素。

def append(self, new_element):current = self.headif self.head:while current.next:current = current.nextcurrent.next = new_elementelse:self.head = new_element2、get_position方法

獲得與傳入參數對應的鏈表中的元素位置。

需要通過循環調用.next屬性來遍歷鏈表。不同的是我們需要定義一個變量counter來記錄我們遍歷的鏈表元素順序。我們還需要在傳入的參數獲取不到鏈表元素時返回None。

def get_position(self, position):counter = 1current = self.headif position < 1:return NoneWhile current and counter <= position:if counter == position:return currentcurrent = current.nextcounter += 1return None

到此這篇關于python鏈表類中獲取元素實例方法的文章就介紹到這了,更多相關python鏈表類中如何獲取元素內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区