Skip to content

Instantly share code, notes, and snippets.

@dashsaurabh
Created January 18, 2020 11:53
Show Gist options
  • Save dashsaurabh/342b53385b72858575bd7f9575da10f2 to your computer and use it in GitHub Desktop.
Save dashsaurabh/342b53385b72858575bd7f9575da10f2 to your computer and use it in GitHub Desktop.
Remove nth or kth node from a singly linked list in single pass
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let dummyNode = new ListNode(0);
dummyNode.next = head;
let first = dummyNode;
let second = dummyNode;
let counter = 0;
while(counter < n + 1){
first = first.next;
counter++;
}
while(first !== null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummyNode.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment