Java solution using 2 pointers with one pass


  • 0
    Y
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode end = head;
        ListNode beforeRemove = head;
        if(head.next == null) return null;
        
        while(end.next != null){
            if(n > 0){
                end = end.next;
                n--;
            }
            else {
                beforeRemove = beforeRemove.next;
                end = end.next;
            }
        }
        while(n > 0){
            head = head.next;
            n--;
        }
        beforeRemove.next = beforeRemove.next.next;
        
        return head;
    }

Log in to reply
 

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