Remove Element from the single linked list
February 1, 2023
Problem
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 be
solution(l, k) = [1, 2, 4, 5]
; - For
l = [1, 2, 3, 4, 5, 6, 7]
andk = 10
, the output should be
solution(l, k) = [1, 2, 3, 4, 5, 6, 7]
.
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.
Solution
- The solution is straight forward, iterate linked list if
cursor
value equals withk
skip cursor value by usingprev.Next
=cursor.Next
Talk is cheap, I show you the code. lol
- create head that contains
*ListNode
and storehead
on theprev
, because we cannot get previous ListNode from current Node - Iterate linked-list using help
cursor
- If current
cursor
value equals withk
then delete current cursor by skipping current node - Otherwise update prev with current cursor
- Return
head.next