Published on

# Remove Element from the single linked list

Authors

## 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]` and `k = 3`, the output should be
`solution(l, k) = [1, 2, 4, 5]`;
• For `l = [1, 2, 3, 4, 5, 6, 7]` and `k = 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 with `k` skip cursor value by using `prev.Next` = `cursor.Next`

Talk is cheap, I show you the code. lol

• create head that contains `*ListNode` and store `head` on the `prev`, because we cannot get previous ListNode from current Node
• Iterate linked-list using help `cursor`
• If current `cursor` value equals with `k` then delete current cursor by skipping current node
• Otherwise update prev with current cursor
• Return `head.next`
solution.go
`_20// Singly-linked lists are already defined with this interface:_20// type ListNode struct {_20// Value interface{}_20// Next *ListNode_20// }_20//_20func solution(l *ListNode, k int) *ListNode {_20 head:=&ListNode{Next:l}_20 prev:= head_20 _20 for cursor:=l;cursor!=nil;cursor=cursor.Next{_20 if cursor.Value.(int) == k {_20 prev.Next = cursor.Next_20 }else{_20 prev = cursor_20 }_20 }_20 _20 return head.Next_20}`