LEEDCODE 203移除链表元素

cpp 复制代码
/**
 * 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* removeElements(ListNode* head, int val) {
        if(head == nullptr)
        {
            return nullptr;
        }
        ListNode* _dummyhead = new ListNode(0);
        _dummyhead->next = head;

        ListNode* pre = _dummyhead;
        ListNode* cur = _dummyhead->next;
        while(cur)
        {
            if(cur->val == val)
            {
                ListNode* p = cur;
                pre->next = cur->next;
                cur = cur->next;
                delete p;

            }
            else
            {
                cur = cur->next;
                pre = pre->next;

            }
        }
        return _dummyhead->next;

        
    }
};
相关推荐
平行侠1 小时前
33水库抽样 - 从未知大小的流中等概率采样
数据结构·算法
Controller-Inversion1 小时前
42. 接雨水
数据结构·算法·leetcode
Controller-Inversion1 小时前
33. 搜索旋转排序数组
数据结构·算法·leetcode
宵时待雨2 小时前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin2 小时前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
L_09072 小时前
【C++】STL— 封装红黑树以实现map 和 set
数据结构·c++
此生决int3 小时前
快速复习之数据结构篇——二叉树(三)
数据结构
Liangwei Lin3 小时前
LeetCode 78. 子集
数据结构·算法·leetcode
炽烈小老头3 小时前
【每天学习一点算法 2026/05/11】排序链表
学习·算法·链表
khalil10203 小时前
代码随想录算法训练营Day-48 单调栈02 | 42. 接雨水、84.柱状图中最大的矩形
数据结构·c++·算法·leetcode·单调栈·接雨水