I am trying to call/print the following linked list:
#--the following code is taken from the most upvoted solution at codesignal--
class ListNode(object):
def __init__(self, x):
self.value = x
self.next = None
def removeKFromList(l, k):
c = l
while c:
if c.next and c.next.value == k:
c.next = c.next.next
else:
c = c.next
return l.next if l and l.value == k else l
I want to call/instantiate the class with l = [3, 1, 2, 3, 4, 5] and k = 3
and I am expecting it to return => [1, 2, 4, 5]
Basically, I am not able to first instantiate the ListNode
class and then call the removeKFromList
method inside it..
You can find this challenge at: https://app.codesignal.com/interview-practice/task/gX7NXPBrYThXZuanm/description
Description:
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]
andk = 3
, the output should beremoveKFromList(l, k) = [1, 2, 4, 5]
For
l = [1, 2, 3, 4, 5, 6, 7]
andk = 10
, the output should beremoveKFromList(l, k) = [1, 2, 3, 4, 5, 6, 7]
Input/Output
execution time limit: 4 seconds (py3)
input:
linkedlist.integer l
A singly linked list of integers.
Guaranteed constraints:
- 0 ≤ list size ≤ 105,
- -1000 ≤ element value ≤ 1000.
input:
integer k
An integer.
Guaranteed constraints:
- -1000 ≤ k ≤ 1000.
output:
linkedlist.integer
Return
l
with all the values equal tok
removed.