My recursive one pass Java solution


  • 0
    Y

    public class Solution {

    int count;
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        helper(dummy, n);
        return dummy.next;
    }
    
    public void helper(ListNode node, int n) {
        if(node.next == null) {
            count = 0;
        } else {
            helper(node.next, n);
        }
        if(count == n) {
            if(n == 1) {
                node.next = null;
            } else {
                ListNode temp = node.next;
                node.next = node.next.next;
                temp.next = null;
            }
        }
        count++;
    }
    

    }


Log in to reply
 

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