Sponsored
Sponsored
This approach involves using a dummy node to handle the removal of nodes, including edge cases where the head node itself needs to be removed. We use a pointer to traverse the list, comparing each node's value with the target val
. If the node needs to be removed, we adjust the pointers to skip the node. If not, we just move to the next node.
Time Complexity: O(n), where n is the number of nodes in the linked list, as we must traverse all nodes.
Space Complexity: O(1) because we are using constant extra space.
1public class ListNode {
2 public int val;
3 public ListNode next;
4 public ListNode(int val = 0, ListNode next = null) {
5 this.val = val;
6 this.next = next;
7 }
8}
9
10public class Solution {
11 public ListNode RemoveElements(ListNode head, int val) {
12 ListNode dummy = new ListNode(0);
13 dummy.next = head;
14 ListNode current = dummy;
15 while (current.next != null) {
16 if (current.next.val == val) {
17 current.next = current.next.next;
18 } else {
19 current = current.next;
20 }
21 }
22 return dummy.next;
23 }
24}
We initialize with a dummy node to manage the removal process smoothly without special conditions for the head. The current node progresses through the list. Nodes are removed by modifying the next pointers. At the conclusion, after addressing all nodes, the modified list is returned.
This approach employs a recursive strategy to tackle the problem. The idea is to attempt removing elements starting from the rest of the list and linking the current node to the result of this removal. If the head node itself needs removal, simply return the result of removing nodes from the rest of the list by moving the reference forward.
Time Complexity: O(n), as each node is processed exactly once.
Space Complexity: O(n), due to the recursion stack for n nodes in the longest path.
1
This solution employs a recursive function that processes the rest of the list first and then makes a decision about the current node. If the current node’s value matches val
, the function returns the next node as the new head; otherwise, it returns itself linked to the result of the processed rest.