Remove Element from the single linked list

Remove Element from the single linked list

February 1, 2023

Moch Lutfi
Name
Moch Lutfi
Twitter
@kaptenupi

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

// Singly-linked lists are already defined with this interface:
// type ListNode struct {
// Value interface{}
// Next *ListNode
// }
//
func solution(l *ListNode, k int) *ListNode {
head:=&ListNode{Next:l}
prev:= head
for cursor:=l;cursor!=nil;cursor=cursor.Next{
if cursor.Value.(int) == k {
prev.Next = cursor.Next
}else{
prev = cursor
}
}
return head.Next
}