Java solution using recursion


  • 6
    J
      public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode cur = head;
        int count = helper(cur, 0, n);
        if (count+1 == n) head = head.next;
        return head; 
    }
    
    public int helper(ListNode head, int count, int target) {
        if (head == null || head.next == null) {
            return 0;
        }
        count = helper(head.next, count, target);
        count++;
        if (count == target) {
            head.next = head.next.next;
        }
        return count;
    }

  • 0
    K
    This post is deleted!

Log in to reply
 

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