Given the head of a linked list, remove the nth node from the end of the list and return its head.
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Solution:
We count the size of the linked list.
To find them nth node from the end we just need to subtract n from count. That is the trick!
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode i = head;
int count = 0;
while(i!=null)
{
i=i.next;
count++;
}
int m = count-n;
ListNode it = head;
int j=0;
while(j<m-1)
{
it=it.next;
j++;
}
if(count==n)
{
return head.next;
}
if(it.next!=null )
it.next = it.next.next;
if(count==1 && n==1) return null;
return head;
}
}