class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || head.next == null) {
return null;
}
ListNode dummy = new ListNode();
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
// advance fast node till the nth node
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
// advance both nodes till fast != null
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
// slow now is at the node before the node that has to be deleted
// bypass the nth node that be to be deleted
// so we just do not reference that node anymore
slow.next = slow.next.next;
return dummy.next;
}
}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)