# 1. Introduction

This blog post explores a common problem in linked list manipulation: removing all nodes from a linked list that have a specific value. This task tests one's ability to traverse and modify a linked list.

## Problem

Given the head of a linked list and an integer val, the objective is to remove all nodes from the linked list that have Node.val == val, and then return the new head of the modified list.

# 2. Solution Steps

1. Handle edge cases where the list is empty or all nodes need to be removed.

2. Use two pointers, prev and current, to traverse the list.

3. Remove nodes with the target value by adjusting the next pointer of the prev node.

4. Return the new head of the list.

# 3. Code Program

``````#include <iostream>
using namespace std;

// ListNode structure definition
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

// Function to remove elements from the list
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy = new ListNode(0);
ListNode *prev = dummy, *current = head;

while (current) {
if (current->val == val) {
prev->next = current->next;
delete current; // Free memory
current = prev->next;
} else {
prev = current;
current = current->next;
}
}

delete dummy; // Free memory
}

// Function to print the linked list
cout << head->val << " -> ";
}
cout << "nullptr\n";
}

int main() {

int val = 6;
printList(head); // Expected output: 1 -> 2 -> 3 -> 4 -> 5 -> nullptr
return 0;
}

``````

### Output:

```1 -> 2 -> 3 -> 4 -> 5 -> nullptr
```

### Explanation:

The removeElements function creates a dummy node to simplify the removal of nodes, especially when the head node needs to be removed. The function then iterates over the list using two pointers, prev and current. If current points to a node with the target value, it is removed, and prev is updated to bypass the deleted node. If current does not have the target value, both pointers move forward. Finally, the function returns the new head of the list, ensuring all nodes with the target value are removed.