https://leetcode.com/problems/delete-nodes-from-linked-list-present-in-array/
3217. Delete Nodes From Linked List Present in Array
要刪掉linked list裡值跟array元素一樣的node
思路:
先把nums轉成set
再traverse list查set看node是不是要刪
最後回傳改完的head
C++ code:
class Solution {
public:
ListNode* modifiedList(vector<int>& nums, ListNode* head) {
ListNode *dummy = new ListNode(0, head);
ListNode *prev = dummy, *cur = head;
unordered_set<int> set;
for(auto n : nums){
set.insert(n);
}
while(cur != nullptr){
if(set.count(cur->val)){
prev->next = cur->next;
delete cur;
cur = prev->next;
} else {
prev = cur;
cur = cur->next;
}
}
ListNode *ans = dummy->next;
delete dummy;
return ans;
}
};