Remove Linked List Elements

Pierre-Marie Poitevin
1 min readMay 7, 2024

In this exercise, we need to remove the nodes with value val from a linked list.

Algorithm

We handle 3 cases in the recursion:

  1. head is null, return null
  2. head.val is val, return removeElements(head.next)
  3. head.val is not val, return head -> removeElements(head.next)

Code

From these 3 cases, we obtain the code below:

public ListNode removeElements(ListNode head, int val) {
if (head == null) {…

--

--