Remove Nth node at the end of LinkedList
- Find the size of LinkedList
- Find the pos of Nth element from start ( size - n )
- Traverse till you reach the prev position to that node
- Point the prev node to next's next node(prev.next = prev.next.next)
- Use Fast & Slow pointer
- Move the
Fast
Pointer to N nodes ahead ofslow
pointer - Move both
fast
&slow
pointers one node at a time tillfast
node reaches null Slow
node now points to previous node of target node, change theslow
pointer node to target nodes next node.
Brute force
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || head.next == null) {
return null;
}
ListNode temp = head;
int size = 1;
while ( (temp = temp.next) != null ) {
++size;
}
if(n > size) {
return null;
}
if(size == n) {
temp = head.next;
head.next = null;
head = temp;
return temp;
}
size = size - n;
temp = head;
while(size > 1) {
temp = temp.next;
--size;
}
System.out.println(temp.val);
temp.next = temp.next.next;
return head;
}
}
Optimized Approach
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
for(int i = 0; i < n; i++) {
fast = fast.next;
}
while( fast.next != null ) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}