怎么在python中对链表进行反转

  介绍

本文章向大家介绍怎么在python中对链表进行反转,主要包括怎么在python中对链表进行反转的使用实例,应用技巧,基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

python主要用来做什么

python主要应用于:1,网络开发;2、数据科学研究;3,网络爬虫;4、嵌入式应用开发,5日游戏开发;6桌面应用开发。

<强>第一种方式:循坏迭代

循坏迭代算法需要三个临时变量:前,头,接下来,临界条件是链表为没有或者链表就只有一个节点。

#,编码:utf - 8   class 节点(对象):   def  __init__(自我):   时间=self.value 没有   时间=self.next 没有   def  __str__(自我):   return  str (self.value)   def  reverse_loop(负责人):   not  if  not  head ,或是;head.next:   return 头   时间=pre  None    while 头:   #=next  head.next 缓存当前节点的向后指针,待下次迭代用   #=head.next  pre 这一步是反转的关键,相当于把当前的向前指针作为当前节点的向后指针   时间=pre  head  #,作为下次迭代时的(当前节点的)向前指针   时间=head  next  #,作为下次迭代时的(当前)节点   return  pre  #,返回头指针,头指针就是迭代到最后一次时的头变量(赋值给了pre)

测试一下:

if  __name__ ==, & # 39; __main__ # 39;:   时间=three 节点()   时间=three.value  3   时间=two 节点()   时间=two.value  2   时间=two.next  3   时间=one 节点()   one.value =1   时间=one.next  2   时间=head 节点()   head.value =0   head.next =,   时间=newhead  reverse_loop(头)   while  newhead:   print (newhead.value,,)   newhead =newhead。下一个

输出:

3   2   1   0   2

怎么在python中对链表进行反转

<强>第二种方式:递归

递归的思想就是:

head.next =,没有   head.next.next =head.next   head.next.next.next =head.next.next   …   …

的负责人向后指针的向后指针转换成头的向后指针,依此类推。

实现的关键步骤就是找到临界点,何时退出递归,当头部。下为时,没有一个说明已经是最后一个节点了,此时不再递归调用。

def  reverse_recursion(负责人):   not  if  not  head ,或是;head.next:   return 头   时间=new_head  reverse_recursion (head.next)   head.next.next =,   时间=head.next 没有   return  new_head

到此这篇关于怎么在python中对链表进行反转的文章就介绍到这了,更多相关的内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

怎么在python中对链表进行反转