Java recursion version


  • 0
    H
    public static ListNode removeNthFromEnd(ListNode head, int n) {
    	if (head == null) {
    		return head;
    	}
    	ListNode dummy = new ListNode(-1);
    	dummy.next = head;
    	removeNode(dummy, n);
    	return dummy.next;
    }
    
    public static int removeNode(ListNode root, int n) {
    	if (root == null) {
    		return 0;
    	}
    	int x = removeNode(root.next, n);
    	if (x == n) {
    		root.next = root.next.next;
    	}
    	return x + 1;
    }

Log in to reply
 

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