听说你会用“栈、迭代、递归“实现链表反转?还有图解?

三种方法的比较:

  1. 用栈实现简单易懂,但是用到栈结构,空间复杂度增加,同时遍历了两边数组,时间复杂度增加
  2. 用迭代实现快速便捷,空间复杂度和时间复杂度都很小
  3. 用递归方法实现,在时间复杂度上并没有很多增加,但是我们知道递归方法的性能稍有欠缺,容易引起内存溢出,在执行过程中多次调用方法

用栈实现

栈的结构是先进后出,就先把节点都放进去,然后再都取出来就好


public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode node = head;
        Stack<ListNode> stack = new Stack<ListNode>();
        while(node.next != null){
            stack.push(node);
            node = node.next;
        }
        ListNode resultNode = node;
        while(!stack.isEmpty()){
            node.next = stack.pop();
            node = node.next;
        }
        node.next = null;
        return resultNode;
    }

按照惯例应该来个图,但是我觉得你这么聪明栈结构一想就出来啦哈,来个养眼的
在这里插入图片描述

迭代实现

代码:

 public static NodeListed reverse(NodeListed head){
        NodeListed pre = null;
        NodeListed curl = head;
        while(curl != null){
            NodeListed next = curl.next;
            curl.next = pre;
            pre = curl;
            curl = next;
        }
        return pre;
    }

初始状态
在这里插入图片描述
进行第一次循环变迁的过程,这次不太明显,别担心还有第二次的
在这里插入图片描述
第二次变迁,后面的和这个都一样,所以来看看
在这里插入图片描述
有没有发现0和1已经倒过来啦?
什么还没看明白,最多第三次啦啊
在这里插入图片描述
好啦这些3成了头部啦,一次循环,pre一直向后走,最后指向9的之后就完毕啦
bingo

递归实现

 public static NodeListed reverse2(NodeListed head){
        if(head==null||head.next==null){
            return head;
        }
        NodeListed newNode = reverse2(head.next);
        head.next.next = head;
        head.next = null;
        return newNode;
    }

递归的话和迭代类似,不过递归是从后向前,来一起看看

初始链表:
在这里插入图片描述
在这里插入图片描述
当上图中的参数(head.next)是9的时候,开始返回,此时head指向8
在这里插入图片描述

当head指向7的时候
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值