Recursive Java 1ms solution without using fast/slow node


  • 1
    D
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            return removeRec(null, head, n) == n ? head.next : head;
        }
        
        public int removeRec(ListNode prev, ListNode head, int n) {
            if(head == null)
            {
                return 0;
            }
            
            int depth = removeRec(head, head.next, n) + 1;
            
            if(n == depth && prev!= null)
            {
                prev.next = head.next;    
            }
            
            return depth;
        }
    }
    

Log in to reply
 

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