[剑指offer] 反转链表 java 两种方法

本文详述了两种链表逆序算法:迭代法与递归法。迭代法通过三个指针pre、head、next操作,实现链表节点指向反转;递归法则从链表尾部开始,逐步调整节点指向。附有清晰图解,便于理解。

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

https://blog.youkuaiyun.com/FX677588/article/details/72357389

上面这篇博客的图解很清晰,看不懂代码可以看这里

 第一种方法:迭代

head表示当前节点,pre是head的前一个节点,next是head的后一个节点。

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null) return null;
        ListNode pre =null;
        ListNode next=null;
        while(head!=null){
            next=head.next;//一定要先把next节点保存,不然链表会断开
            head.next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }
}

 第二种方法:递归

先遍历到表尾,再改变指针方向。

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode pre=ReverseList(head.next);
        head.next.next=head;
        head.next=null;//防止链表形成环
        return pre;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值