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,
- Leetcode Remove Nth Node From End of List problem solution in C++
- Leetcode Remove Nth Node From End of List problem solution in C
- Leetcode Remove Nth Node From End of List problem solution in Python
- Leetcode Remove Nth Node From End of List problem solution in C#