Last active
August 20, 2023 17:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
@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!
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
@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;
}