Remove Element from the single linked list

1 min read Tweet this post

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.

  • 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

<CH.Section>

// 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
}

</CH.Section>

go data-structure linked-list