Recursive solution in Java


  • 0
    R
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (util(head, n) == 0) {
                head = head.next;
            }
            return head;
        }
        private int util(ListNode node, int n) {
            if (node.next == null) {
                return n-1;
            }
            n = util(node.next, n);
            if (n == 0) {
                if (node.next != null) {
                    node.next = node.next.next;
                }
            }
            return n-1;
        }
    }
    

Log in to reply
 

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