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;

        
    }
};
相关推荐
Tingjct1 天前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
C雨后彩虹1 天前
计算疫情扩散时间
java·数据结构·算法·华为·面试
飞机和胖和黄1 天前
考研之王道C语言第三周
c语言·数据结构·考研
达文汐1 天前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗1 天前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
执着2591 天前
力扣hot100 - 234、回文链表
算法·leetcode·链表
Gorgous—l1 天前
数据结构算法学习:LeetCode热题100-多维动态规划篇(不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离)
数据结构·学习·算法
一条大祥脚1 天前
26.1.26 扫描线+数论|因子反演+子序列计数|树套树优化最短路
数据结构·算法
踩坑记录1 天前
leetcode hot100 23. 合并 K 个升序链表 hard 分治 迭代
leetcode·链表
李老师讲编程1 天前
C++信息学奥赛练习题-杨辉三角
数据结构·c++·算法·青少年编程·信息学奥赛