Skip to content

Instantly share code, notes, and snippets.

@IEdiong
Last active April 17, 2022 15:18
Show Gist options
  • Save IEdiong/21101d240c2fc01d5268635fac15a760 to your computer and use it in GitHub Desktop.
Save IEdiong/21101d240c2fc01d5268635fac15a760 to your computer and use it in GitHub Desktop.
Code Signal: removeKFromList solution -- Interview Practice__Linked List - 01 (Easy)
// Singly-linked lists are already defined with this interface:
// function ListNode(x) {
// this.value = x;
// this.next = null;
// }
//
function solution(l, k) {
if (l === null) return l; // return if the linked list is empty
let dummyNode = new ListNode(); // create a dummy node whose next points to the head of the given Linked List
dummyNode.next = l;
let curr = l, prev = dummyNode; // set up two pointers to track the current node and the previous node
while (curr) { // loop through the Linked List
if (curr.value === k) { // if the value of the node matches 'k'
prev.next = curr.next; // delete the node from the Linked List
} else { // else
prev = curr; // move the previous pointer forward
}
curr = curr.next; // move the current pointer forward
}
return dummyNode.next; // return the head of the new Linked List
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment