leetcode 3217 从链表中移除在数组中存在的节点
一、题目描述


二、解题思路
整体思路
可以采用哈希表(或者集合)+循环模拟的方法来解决这个问题。
具体思路
(1)首先,定义哈希表来标记nums中存在的元素;
unordered_map<int,bool> hash;
for(auto x:nums) hash[x]=true;
(2)接着,我们进行循环模拟的准备工作;
<1>为了保证后续节点的一致性,我们引入新头节点newhead;
<2>pre指针用于记录当前处理位置的前一个位置,避免位置丢失,初始化为&newhead;current指针用于指向当前正在处理的位置,初始化为head;
ListNode newhead(0);
newhead.next=head;
ListNode* pre=&newhead;
ListNode* current=head;
(3)然后,我们通过循环来模拟这个解题过程,当current不为空时进行循环:
<1>如果current指向的值在nums中出现了,即hash.count(current->val)>0,就移除这个节点,并进行指针更新;
<2>如果current指向的值没有在nums中出现,就直接进行指针更新;
while(current!=nullptr){
//current指向的值在nums中存在
if(hash.count(current->val)>0){
pre->next=current->next;
//delete current;(可以不写,因为链表可能底层实现方式不能delete)
current=pre->next;
}
else{
pre=current;
current=current->next;
}
}
(4)返回处理完的链表。ret用于承接最终的返回结果,即newhead.next;
ListNode* ret=newhead.next;
return ret;
注意:相比于ListNode* Newhead=new ListNode(0),直接申请一个ListNode变量可以免去后续的释放环节。
三、代码实现
/*** 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) {//将nums中的元素加入哈希表unordered_map<int,bool> hash;for(auto x:nums) hash[x]=true;//引入虚拟头节点ListNode newhead(0);newhead.next=head;ListNode* pre=&newhead;ListNode* current=head;while(current!=nullptr){//current指向的值在nums中存在if(hash.count(current->val)>0){pre->next=current->next;//delete current;(可以不写,因为链表可能底层实现方式不能delete)current=pre->next;}else{pre=current;current=current->next;}}ListNode* ret=newhead.next;return ret;}
};