1ms Java Solution. Recursive.

  • 0
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) return null;
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        removeNthFromEndAux(dummyHead, n);
        return dummyHead.next;
    private int removeNthFromEndAux(ListNode head, int n) {
        if (head == null) return 0;
        int countTh = removeNthFromEndAux(head.next, n);
        if (countTh == n) {
            head.next = head.next.next;
        return 1 + countTh; 

  • 0

    I think actually you are using two passes. In the first pass your recursive functions visited all nodes find the last node. In the second pass your recursive functions counted back and deleted the nth node. What's more, your solution stored all of the nodes implicitly in the parameter "head" of your recursive function, which can take some extract space.

Log in to reply

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