Java Recursive Without Helper


  • 4
    T

    Just another way of doing it.

    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null) return null;
            
            ListNode next = head.next;
    
            // Used to set next of root to null. It will get overridden by "next.next = head" in the method that 
            // called this one if "head" is not root
            head.next = null;
            
            if(next != null) {
                ListNode root = reverseList(next);
                next.next = head;
                return root;
            }
            
            return head;
        }
    }

  • 1
    D

    Simpler solution. Inspired by your code.

    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
    
        ListNode next = head.next;
        head.next = null;
    
        ListNode root = reverseList(next);
        next.next = head;
        return root;
    }

Log in to reply
 

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