Leetcode Remove Nth Node From End of List problem solution in Java programming

In the Leetcode Remove Nth Node From End of List problem solution in Java programming Given the head of a linked list, remove the nth node from the end of the list and return its head.

Leetcode Remove Nth Node From End of List problem solution in Java programming

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // base case
        if (head.next == null) {
            return null;
        }
        
        //size of linkedlist
        int size = 0;
        ListNode curr = head;
        while (curr != null) {
            curr = curr.next;
            size++;
        }
        
        //removing SIZEth node from last i.e. head
           if(n == size) {
               return head.next;
           }

        
        // calculate the previous node before the nth node to be deleted
        int indexOfPrev = size - n;
        int i = 1;
        ListNode prev = head;
        while (i < indexOfPrev) {
            prev = prev.next;
            i++;
        }
        
        prev.next = prev.next.next;
        return head;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *