Remove Linked List Elements
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:
- head is null, return null
- head.val is val, return removeElements(head.next)
- 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) {…