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

向鏈表添加元素后。在鏈表中,不能通過索引來定位每個元素,只能在列表中定位。鏈表元素的.next方法需要被持續(xù)調用,以獲得下一個元素,并最終獲得最后一個元素。最后一個元素的.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方法
獲得與傳入參數對應的鏈表中的元素位置。
需要通過循環(huán)調用.next屬性來遍歷鏈表。不同的是我們需要定義一個變量counter來記錄我們遍歷的鏈表元素順序。我們還需要在傳入的參數獲取不到鏈表元素時返回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學習網。
網頁名稱:創(chuàng)新互聯Python教程:python鏈表類中如何獲取元素
當前URL:http://m.fisionsoft.com.cn/article/cddjjgc.html


咨詢
建站咨詢
