当前位置:首页 » python教程 » 正文

python链表类中获取元素实例方法

看: 677次  时间:2021-03-24  分类 : python教程

1、append方法

向链表添加元素后。在链表中,不能通过索引来定位每个元素,只能在列表中定位。链表元素的.next方法需要被持续调用,以获得下一个元素,并最终获得最后一个元素。最后一个元素的.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方法

获得与传入参数对应的链表中的元素位置。

需要通过循环调用.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链表类中如何获取元素内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!