Created
November 7, 2019 17:27
-
-
Save HaiBV/d5becb23bc4f916425f8458f4fa67e35 to your computer and use it in GitHub Desktop.
removeKFromList
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
// Singly-linked lists are already defined with this interface: | |
// function ListNode(x) { | |
// this.value = x; | |
// this.next = null; | |
// } | |
// | |
function removeKFromList(l, k) { | |
var curr; | |
// remove leading k values with changing l | |
while (l && l.value == k) { | |
l = l.next; | |
} | |
// loop to the end. | |
// skip nodes with k values. | |
curr = l; | |
while (curr && curr.next) { | |
if (curr.next.value == k) { | |
curr.next = curr.next.next; | |
} else { | |
curr = curr.next; | |
} | |
} | |
return l; | |
} | |
function removeKFromListRecursion(l, k) { | |
if(l===null) return null; | |
else { | |
l.next = removeKFromList(l.next,k); | |
return (l.value===k)?l.next:l | |
} | |
} | |
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].
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://app.codesignal.com/interview-practice/task/gX7NXPBrYThXZuanm/description