剑指 Offer 24. 反转链表(第一反应的方法->双指针->递归)

文章提供了三种方法来反转链表:1)使用栈和数组创建新链表,2)采用双指针技术,3)使用递归。每种方法都有详细的代码实现,并解释了其工作原理。

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

剑指 Offer 24. 反转链表

题目:

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

 1.简单容易理解--创建新的链表

第一反应就是用栈存数值,但其实用数组就可以了。

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head==null)return null;
        ListNode curHead = head;
        Stack<Integer> stack = new Stack<>();
        while (curHead!=null){
            stack.push(curHead.val);
            curHead = curHead.next;
        }
        ListNode res = new ListNode(stack.pop());
        while (!stack.isEmpty()){
            res.next = new ListNode(stack.pop());
            res = res.next;
        }
        return res;
    }
}

2.双指针

 图解:

最后一个指向null,因此pre初始值为null, temp临时保存cur的下一个, 改变cur的next的指向方向,当cur==null时,遍历结束。

public class Solution {
//双指针
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur!=null){
            //要记录cur后面的Node,指针才能向后移动
            ListNode temp = cur.next;
            //改变next指向方向
            cur.next = pre;
            //移动   要先移动pre,后移动cur,若先移动cur,pre要指向的cur已经变动
           pre = cur;
           cur = temp;
        }
        return pre;
    }
}

3.递归:

 解题思路和双指针一样,注意递归的终止条件和递归的传参。

public class Solution {
    //递归
    public ListNode reverseList(ListNode head) {
        if (head == null) return null;
        ListNode pre = null;
        ListNode cur = head;
        return reverse(pre, cur);
    }

    private ListNode reverse(ListNode pre, ListNode cur) {
        if (cur == null) return pre;

        ListNode temp = cur.next;
        //改变方向
        cur.next = pre;
        return reverse(cur, temp);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小俱的一步步

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

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

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

打赏作者

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

抵扣说明:

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

余额充值