python链表类中如何获取元素
python链表类中如何获取元素
1、append方法
向链表添加元素后。在链表中,不能通过索引来定位每个元素,只能在列表中定位。链表元素的.next方法需要被持续调用,以获得下一个元素,并最终获得最后一个元素。最后一个元素的.next属性中将指向新添加的元素。
defappend(self,new_element):
current=self.head
ifself.head:
whilecurrent.next:
current=current.next
current.next=new_element
else:
self.head=new_element
2、get_position方法
获得与传入参数对应的链表中的元素位置。
需要通过循环调用.next属性来遍历链表。不同的是我们需要定义一个变量counter来记录我们遍历的链表元素顺序。我们还需要在传入的参数获取不到链表元素时返回None。
defget_position(self,position):
counter=1
current=self.head
ifposition<1:
returnNone
Whilecurrentandcounter<=position:
ifcounter==position:
returncurrent
current=current.next
counter+=1
returnNone
以上就是python链表类中获取元素的方法,希望能对大家有所帮助,更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






