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

In the Leetcode Remove Nth Node From End of List problem solution in C# 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 C# programming

public class Solution {
    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        var right = head;
        for(int i = 0; i< n; i ++)
        {
            right = right.next;
            //Reached the end
            if(right == null)
            {
                //If there's only one node
                if(head.next == null)
                    return null;
                else 
                    return head.next;
            }              
        }
        
        var left = head;
        while(right.next!=null)
        {
            left = left.next;
            right = right.next;            
        }
        
        left.next = left.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 *