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;

        
    }
};
相关推荐
仰泳的熊猫8 小时前
1077 Kuchiguse
数据结构·c++·算法·pat考试
LYFlied8 小时前
【每日算法】LeetCode 19. 删除链表的倒数第 N 个结点
算法·leetcode·链表
阿里巴巴AI编程社区8 小时前
Qoder 提效实战:数据开发工程师用 Qoder 提效50%
数据结构
消失的旧时光-19438 小时前
从 C 链表到 Android Looper:MessageQueue 的底层原理一条线讲透
android·数据结构·链表
夏乌_Wx9 小时前
练题100天——DAY28:找消失的数字+分发饼干
数据结构·算法
lzh200409199 小时前
二叉搜索树与双向链表
数据结构·链表
WolfGang0073219 小时前
代码随想录算法训练营Day48 | 108.冗余连接、109.冗余连接II
数据结构·c++·算法
45288655上山打老虎10 小时前
List容器
数据结构·windows·list
LYFlied10 小时前
【每日算法】LeetCode 234. 回文链表详解
算法·leetcode·链表
NeDon11 小时前
[OJ]数据结构:移除链表元素
c语言·数据结构·算法·链表