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.
1#include <stdlib.h>
2
3struct ListNode {
4 int val;
5 struct ListNode *next;
6};
7
8struct ListNode* removeElements(struct ListNode* head, int val) {
9 struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
10 dummy->next = head;
11 struct ListNode *current = dummy;
12 while (current->next != NULL) {
13 if (current->next->val == val) {
14 struct ListNode *temp = current->next;
15 current->next = current->next->next;
16 free(temp);
17 } else {
18 current = current->next;
19 }
20 }
21 struct ListNode *newHead = dummy->next;
22 free(dummy);
23 return newHead;
24}
We create a dummy node that points to the head of the list to handle edge cases seamlessly. The current pointer is initialized to the dummy node. We traverse the linked list, and if the next node's value equals the target val
, we adjust the pointers to remove it. Otherwise, we move the current pointer forward. Finally, we free the dummy node and return the new head of the list.
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.