Day87 | 灵神 | 前后指针 移除链表元素 从链表中移除在数组中存在的节点

203.移除链表元素

203. 移除链表元素 - 力扣(LeetCode)

思路:

就是一道easy题目,思路并不难想,就从前往后遍历就行

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *t=new ListNode;
t->next=head;
ListNode *p=t;
while(p->next)
if(p->next->val==val)
{
ListNode *temp=p->next;
p->next=p->next->next;
delete temp;
}
else
p=p->next;
return t->next;
}
};

3217.从链表中移除在数组中存在的节点

3217. 从链表中移除在数组中存在的节点 - 力扣(LeetCode)

思路:

和上一道题的区别就是把nums加入哈希表,然后判断条件变成哈希表里面有没有链表元素,比较简单

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
ListNode* modifiedList(vector<int>& nums, ListNode* head) {
/*
unordered_map<int,int> st;
for(auto c:nums)
st[c]++;*/
unordered_set<int> st(nums.begin(), nums.end());
ListNode *t=new ListNode;
t->next=head;
ListNode *p=t;
while(p->next)
{
/*map的判断条件 st.find(p->next->val)!=st.end()*/
if(st.contains(p->next->val))
p->next=p->next->next;
else
p=p->next;
}
return t->next;
}
};