Java递归实现单链表反转的工作原理及代码疑问解析
单链表反转递归实现的执行逻辑疑问
我正在查阅用于反转给定链表的递归实现函数,对应代码如下:
static Node reverse(Node head) { if(head == null) { return head; } // last node or only one node if(head.next == null) { return head; } Node newHeadNode = reverse(head.next); // change references for middle chain head.next.next = head; head.next = null; // send back new head node in every recursion return newHeadNode; } public static void main(String[] args) throws IOException { LinkedList llist = new LinkedList(); llist.insertNode(20); llist.insertNode(4); llist.insertNode(15); llist.insertNode(85); Node llistReversed = reverse(llist.head); printSinglyLinkedList(llistReversed, " "); }
按照代码的节点插入逻辑,最终构建完成的链表节点序列为:85 15 4 20
我原本认为,调用reverse方法完成处理后,head.next会指向值为15的第二个节点;基于这个认知,我完全无法理解这段代码是如何通过递归流程实现链表反转的。
内容的提问来源于stack exchange,提问作者monkeyBus
相关产品推荐
相关产品推荐

