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.
1class ListNode {
2 int val;
3 ListNode next;
4 ListNode() {}
5 ListNode(int val) { this.val = val; }
6 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
7}
8
9class Solution {
10 public ListNode removeElements(ListNode head, int val) {
11 ListNode dummy = new ListNode(0);
12 dummy.next = head;
13 ListNode current = dummy;
14 while (current.next != null) {
15 if (current.next.val == val) {
16 current.next = current.next.next;
17 } else {
18 current = current.next;
19 }
20 }
21 return dummy.next;
22 }
23}
Use a dummy node to simplify removing nodes, particularly the head. A current pointer traverses the list. When a node's value matches val
, it is skipped by rearranging the pointers. The traversal continues until all nodes are checked. Finally, the list without the removed nodes 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 public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null) {
this.val = val;
this.next = next;
}
}
public class Solution {
public ListNode RemoveElements(ListNode head, int val) {
if (head == null) return null;
head.next = RemoveElements(head.next, val);
return head.val == val ? head.next : head;
}
}
The C# method processes the list recursively. If the node should be removed, it returns the processed form of the rest; if not, the current node remains and links to the subsequent nodes that have been evaluated and possibly pruned.