[LeetCode] Delete Nodes From Linked List Present in Array

3217. Delete Nodes From Linked List Present in Array

You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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* modifiedList(vector<int>& nums, ListNode* head) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = dummy;
unordered_set<int> us(begin(nums), end(nums));
while(head) {
if(!us.count(head->val)) {
runner->next = new ListNode(head->val);
runner = runner->next;
}
head = head->next;
}
return dummy->next;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/14/PS/LeetCode/delete-nodes-from-linked-list-present-in-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.