反转链表最简单的实现方式--python

本文深入探讨了链表数据结构的反转算法实现,通过具体的Python代码示例,详细讲解了如何将一个链表的节点顺序进行反转,为读者提供了理解和应用链表反转算法的实践指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class linkedlist(object):
  def __init__(self, x):
    self.val=x
    self.next=None

def reverse(phead):
  if not phead or not phead.next:
    return phead

  last =None            #头节点变尾节点,所以下一个节点是空
  while phead:
    tmp = phead.next       #先保存头节点的下一个节点,因为要断开连接丢失
    phead.next=last        #将头节点反转方向
    last =phead              #last 变位当前节点
    phead=tmp              # 头节点变为当前头节点的下一个节点,重复上述操作
  return last

测试

node1 = linkedlist(1)
node2 = linkedlist(2)
node3 = linkedlist(3)

node1.next= node2
node2.next = node3

new = reverse(node1)
new.val

3

### 使用Python递归方法反转链表 为了实现链表的递归反转,可以定义一个`Node`类来表示单向链表中的节点。每个节点包含两个属性:数据项`data`以及指向下一个节点的链接`next`。 下面是一个完整的例子,展示了如何创建这样的节点结构并编写用于递归反转链表的方法: ```python class Node: def __init__(self, data=None): self.data = data # 节点的数据部分 self.next = None # 初始设置下一节点为空 def reverse_linked_list_recursive(head): """递归地反转给定的链表""" if head is None or head.next is None: return head new_head = reverse_linked_list_recursive(head.next) head.next.next = head head.next = None return new_head ``` 此函数接受当前列表的第一个节点作为参数,并返回新反转后的第一个节点。当遇到最后一个非空节点时停止递归调用,在回溯过程中改变各节点之间的指针方向[^1]。 对于测试这段代码的效果,可以通过构建简单的链表实例来进行验证: ```python if __name__ == "__main__": # 创建一些节点对象 node1 = Node(1) node2 = Node(2) node3 = Node(3) # 构建原始顺序的链表关系 node1.next = node2 node2.next = node3 reversed_head = reverse_linked_list_recursive(node1) current_node = reversed_head while current_node is not None: print(current_node.data, end=" -> " if current_node.next else "\n") current_node = current_node.next ``` 上述程序会打印出反转之后的新链表序列 `3 -> 2 -> 1`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值