python链表的应用(python链表类中如何获取元素)
导读:1、append方法...
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_element2 、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创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!