头图

递归代码:

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 反转链表 原题解地址


Feyl
18 声望1 粉丝

没有梦想,何必远方?