Skip to content

Instantly share code, notes, and snippets.

@andersonleite
Last active August 20, 2023 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonleite/ff36fc4497b0b199c28d023c247b8df6 to your computer and use it in GitHub Desktop.
Save andersonleite/ff36fc4497b0b199c28d023c247b8df6 to your computer and use it in GitHub Desktop.
Remove all elements from list l that have a value equal to k
// Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, since this is what you'll be asked to do during an interview.
// Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.
// Example
// For l = [3, 1, 2, 3, 4, 5] and k = 3, the output should be
// removeKFromList(l, k) = [1, 2, 4, 5];
// For l = [1, 2, 3, 4, 5, 6, 7] and k = 10, the output should be
// removeKFromList(l, k) = [1, 2, 3, 4, 5, 6, 7].
// Singly-linked lists are already defined with this interface:
// function ListNode(x) {
// this.value = x;
// this.next = null;
// }
//
function removeKFromList(l, k) {
let head = l
let previous = null
while(l){
if(l.value === k){
if(previous===null){
head = l = l.next
continue
} else {
previous.next = l.next
l = l.next
continue
}
}
previous = l
l = l.next
}
return head
}
@kbakande
Copy link

kbakande commented May 22, 2021

@andersonleite, great work you did here. I have been going through your the questions and solutions. Well done. For this particular question (removeKFromList), I think an 'else' is missing.

There should be an else in line 34, like

else {
previous = l ;
l = l.next;
}

@dehanz13
Copy link

dehanz13 commented Jan 11, 2022

@andersonleite, awesome solution here and very clean. One question, can you explain what happens in chaining "head = l = l.next"?

I'm guessing head and l equals to l.next?
Thanks!

@johnykov
Copy link

johnykov commented Aug 20, 2023

comparing to much cleaner java code solution this one is barely readable for me, what is previous? it's not obvious right away

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment