剑指 Offer 24. 反转链表

题目描述:

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

示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

一:迭代

建议看B站课程:
https://www.bilibili.com/video/BV1iB4y1P7PU?p=1

//方法一:迭代
    public static ListNode reverseList1(ListNode head) {
        ListNode pre=null,curr=head,next;
        while(curr!=null){
            next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

二:递归

https://www.bilibili.com/video/BV1iB4y1P7PU?p=2

    //方法二:递归
    public static ListNode reverseList2(ListNode head) {
        if(head==null || head.next==null) {//访问到最后一个元素时就直接返回该节点
            return head;
        }
        ListNode new_head = reverseList2(head.next);//从尾结点返回时是 new_head={val=5, next=null}
        //head={val=4, next={val=5, next=null}}
        head.next.next=head;
        head.next=null;

        return new_head;//经过head.next.next=head;head.next=null;之后 new_head={val=5, next={val=4, next=null}}
    }


递归里面一定要注意的是什么呢,就是出口,以及最末尾的 return new_head,我注释了在元素为4的这个节点返回的结果便于去理解为什么是 new_head 。
我在这里懵逼了接近一个小时,所以最后一定要记录下来。递归算法就是我的黑洞!

测试用的完整代码

package jianzhiOffer;

public class ReverseList24 {

    //方法一:迭代
    public static ListNode reverseList1(ListNode head) {
        ListNode pre=null,curr=head,next;
        while(curr!=null){
            next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

    //方法二:递归
    public static ListNode reverseList2(ListNode head) {
        if(head==null || head.next==null) {//访问到最后一个元素时就直接返回该节点
            return head;
        }
        ListNode follow = reverseList2(head.next);//从尾结点返回时是follow={val=5, next=null}
        //head={val=4, next={val=5, next=null}}
        head.next.next=head;
        head.next=null;

        return follow;//经过head.next.next=head;head.next=null;之后follow={val=5, next={val=4, next=null}}
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1, null);
        ListNode node2 = new ListNode(2, null);
        ListNode node3 = new ListNode(3, null);
        ListNode node4 = new ListNode(4, null);
        ListNode node5 = new ListNode(5, null);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=node5;
        node5.next=null;
        System.out.println(reverseList2(node1));

        System.out.println("============================");
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=node5;
        node5.next=null;
        System.out.println(reverseList1(node1));

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值