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

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

分类: 刷题记录 | Darlingの妙妙屋

203.移除链表元素

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

思路:

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

完整代码:

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加入哈希表,然后判断条件变成哈希表里面有没有链表元素,比较简单

完整代码:

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值