1ms Java Recursion


  • 2
    public class Solution {
        public int removeNthFromEndAux(ListNode node, int n) {
            if(node==null)
                return 0;
            int rIdx = removeNthFromEndAux(node.next, n);
            if (rIdx==n)  // assume n always >= 1, so node.next.next must exist
                node.next = node.next.next;
            return 1+rIdx;
        }
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if(n<=0)
                return head;
            if(head==null)
                return head;
            if(n>=removeNthFromEndAux(head,n)) // will remove head!
                return head.next;
            else
                return head;
        }
    }

Log in to reply
 

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