递归代码:
class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; }}
剖析:
if (head == null || head.next == null) { return head; }
head==null:当第一次输出为null的时候间接返回null,不进行递归操作。
head.next == null:返回链表的最初一个节点
ListNode newHead = reverseList(head.next);
顺着链表节点一直的递归,每层的递归操作都会进行两个节点替换地位的操作;且当递归到最初一个节点的时候会返回最初一个节点(这最初一个节点是反转后链表的头结点)。
head.next.next = head; //节点的下一个节点的后一节点指向本结点head.next = null; //本节点的下一节点指向null(此时本结点前一节点对该结点的指向未发生变化,以便后续本结点与其前一结点替换地位)
替换前后节点的地位。(能够在纸上画一个任意长度的链表,用带箭头的线连贯示意指向关系,思考一下下整个链表节点替换地位的过程)
return newHead;
若链表不为null,通过迭代并将链表的最初节点(反转后变为链表头节点)回溯
if (head == null || ** head.next == null **) { return head;}
作为办法调用后果返回。
LeetCode 反转链表 原题解地址