(编辑:jimmy 日期: 2025/10/28 浏览:2)
本文实例讲述了Python实现链表反转的方法。分享给大家供大家参考,具体如下:
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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。