LeetCode 24 反转链表

LeetCode 24 反转链表

问题描述:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:40.2 MB, 在所有 Java 提交中击败了5.06%的用户

class Solution {
    public ListNode reverseList(ListNode head) {
        /*空链表或只有头节点*/
        if(head==null || head.next==null) {
            return head;
        }

        ListNode next = head.next;
        /*将以next为头节点的子链表进行反转,返回反转链表的头节点(原链表尾节点)*/
        ListNode newHead = reverseList(next);
        /*将head纳入反转链表*/
        next.next = head;
        head.next = null;
        return newHead;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13630533.html