LeetCode-206. 反转链表

本文介绍了两种反转链表的方法:使用双指针和递归。在双指针法中,定义pre和cur两个指针,依次反转局部链表。递归法中,通过递归调用反转链表的子部分,然后连接头节点和反转后的后续节点,最后处理单节点的特殊情况作为递归基。

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

题目来源
206. 反转链表

双指针

定义两个指针: pre 和 cur;pre 在前 cur 在后。
每次让 cur 的 next 指向 pre,实现一次局部反转
局部反转完成之后,pre 和 cur 同时往前移动一个位置
循环上述过程,直至 cur 到达链表尾部

在这里插入图片描述

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}

在这里插入图片描述

递归

输入一个节点 head,将「以 head 为起点」的链表反转,并返回反转之后的头结点。
在这里插入图片描述
那么输入 reverse(head.next) 后,会在这里进行递归:

ListNode last = reverse(head.next);

在这里插入图片描述
这个 reverse(head.next) 执行完成后,整个链表就成了这样:
在这里插入图片描述
reverse 函数会返回反转之后的头结点,我们用变量 last 接收了。
现在再来看下面的代码:

head.next.next = head;

在这里插入图片描述
接下来

head.next = null;
return last;

在这里插入图片描述
递归函数要有 base case,也就是这句:

if (head.next == null) return head;

意思是如果链表只有一个节点的时候反转也是它自己,直接返回即可。

代码实现

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        ListNode last = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return last;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Knight_AL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值