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

    技术2023-08-31  120

    三种方法的比较:

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

    用栈实现

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

    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的时候

    Processed: 0.013, SQL: 9