【Python刷题】反转链表(双指针和递归两种方法)

问题描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
在这里插入图片描述

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

双指针方法

  • 比如一个链表的第一个结点值为1,第二个为2,…,最后一个为5,如上图
  • 定义两个指针 cur 和 pre ,和一个临时指针 temp ,让 cur 指向 head (第一个结点1),pre 指向空 (NULL)
  • 只要 cur 一直存在,则进入 while 循环
  • 令 temp 指针指向 cur 的下一个结点(即2),cur 的下一个指针指向 pre (目前为空)
  • 然后将 cur 和 pre 都往后移一个结点。要注意先移动 pre
  • 依次循环
  • 最后返回 pre
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
    	cur = head
    	pre = None
    	while cur : 
    		temp = cur.next
    		cur.next = pre
    		pre = cur
    		cur = temp
    	return pre

递归方法

  • 判断 head 或 head.next 是否为空,若为空,则返回 head
  • 定义一个 n_head 以 head.next 为参数递归执行该函数,递归结束后,此时 head 为4,head.next 为5
  • 令 head.next.next=head,即令 5 的下一个指针指向 4,从而实现反转,依次递归。。。
  • 最后返回 n_head
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head
        n_head=self.reverseList(head.next)
        head.next.next=head
        head.next=None
        return n_head
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值