Recursive Java solution


  • 2
    L
        public ListNode reverseList(ListNode head) {
            if(head==null|| head.next==null) {
                return head;
            }
            ListNode tail = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return tail;
        }

  • 0
    D

    Can you explain the line head.next.next = head?


  • 0
    L

    (head.next) is the node after head, we want to reverse the direction of (head.next)'s next pointer to point back to head, then set head's next pointer to null so that the last node in the reversed list is null terminated.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.