400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

Python如何实现链表反转-创新互联

小编给大家分享一下Python如何实现链表反转,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

成都创新互联是一家专业提供开阳企业网站建设,专注与成都网站建设、网站设计H5场景定制、小程序制作等业务。10年已为开阳众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。

Python实现链表反转

链表反转(while迭代实现):

class Node(object):
  def __init__(self, value=None, next=None):
    self.value = value
    self.next = next

  @staticmethod
  def reverse(head):
    cur_node = head # 当前节点
    new_link = None # 表示反转后的链表
    while cur_node != None:
      tmp = cur_node.next # cur_node后续节点传递给中间变量
      cur_node.next = new_link  # cur_node指向new_link
      new_link = cur_node  # 反转链表更新,cur_node为新的头结点
      cur_node = tmp  # 原链表节点后移一位
    return new_link

link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9)))))))))
root = Node.reverse(link)
while root:
    print(root.value)
    root =root.next

运行结果:

9
8
7
6
5
4
3
2
1

递归实现:

  def reverse2(head):
    if head.next == None: # 递归停止的基线条件
      return head
    new_head = reverse2(head.next)
    head.next.next = head # 当前层函数的head节点的后续节点指向当前head节点
    head.next = None # 当前head节点指向None
    return new_head

以上是“Python如何实现链表反转”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联成都网站设计公司行业资讯频道!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网页题目:Python如何实现链表反转-创新互联
文章URL:http://www.bluegullmedia.com/article/ccejds.html

其他资讯

让你的专属顾问为你服务

0.7185s