Remove Linked List Elements
Problem
Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
Constraints
- The number of nodes in the list is in the range
[0, 104]
. 1 <= Node.val <= 50
0 <= val <= 50
Solution
The problem Remove Linked List Elements
can be solved by adding a dummy head to the beginning of the given head and removing nodes that has Node.val == val
.
Implementation
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *removeElements(ListNode *head, int val)
{
ListNode *node = new ListNode(-1, head);
head = node;
while (node->next != NULL)
{
if (node->next->val == val)
node->next = node->next->next;
else
node = node->next;
}
return head->next;
}
};