Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created March 23, 2025 20:43
Show Gist options
  • Save primaryobjects/81005065c66a366fc1e8046a05b7467f to your computer and use it in GitHub Desktop.
Save primaryobjects/81005065c66a366fc1e8046a05b7467f to your computer and use it in GitHub Desktop.
Remove nth node from end of list
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
// Traverse to the nth item from the end of the list by using a forward-looking pointer.
let result = head;
let slow = head;
let fast = head;
let parent = null;
// Set fast pointer. When this pointer becomes null, we are on the node to delete.
for (let i=0; i<n; i++) {
fast = fast.next;
}
while (slow != null) {
if (!fast) {
// slow is the node to be deleted.
if (parent || slow.next) {
// Remove the current node.
if (parent) {
parent.next = slow.next;
}
else {
// Remove the first node. We are on the first node, but there are still children.
result = slow.next;
}
break;
}
else {
result = null;
break;
}
}
parent = slow;
slow = slow.next;
fast = fast.next;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment