新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python鏈表類中如何獲取元素
1、append方法

向鏈表添加元素后。在鏈表中,不能通過索引來定位每個元素,只能在列表中定位。鏈表元素的.next方法需要被持續(xù)調(diào)用,以獲得下一個元素,并最終獲得最后一個元素。最后一個元素的.next屬性中將指向新添加的元素。
def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element
2、get_position方法
獲得與傳入?yún)?shù)對應(yīng)的鏈表中的元素位置。
需要通過循環(huán)調(diào)用.next屬性來遍歷鏈表。不同的是我們需要定義一個變量counter來記錄我們遍歷的鏈表元素順序。我們還需要在傳入的參數(shù)獲取不到鏈表元素時返回None。
def get_position(self, position): counter = 1 current = self.head if position < 1: return None While current and counter <= position: if counter == position: return current current = current.next counter += 1 return None
以上就是python鏈表類中獲取元素的方法,希望能對大家有所幫助,更多知識盡在python學(xué)習(xí)網(wǎng)。
網(wǎng)頁標(biāo)題:創(chuàng)新互聯(lián)Python教程:python鏈表類中如何獲取元素
標(biāo)題鏈接:http://www.5511xx.com/article/cddjjgc.html


咨詢
建站咨詢
