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;

        
    }
};
相关推荐
闪电麦坤955 小时前
数据结构:递归的种类(Types of Recursion)
数据结构·算法
小熊猫写算法er5 小时前
终极数据结构详解:从理论到实践
数据结构
-qOVOp-6 小时前
408第一季 - 数据结构 - 栈与队列的应用
数据结构
鑫鑫向栄7 小时前
[蓝桥杯]修改数组
数据结构·c++·算法·蓝桥杯·动态规划
鑫鑫向栄7 小时前
[蓝桥杯]带分数
数据结构·c++·算法·职场和发展·蓝桥杯
sss191s8 小时前
Java 集合面试题从数据结构到 HashMap 源码剖析详解及常见考点梳理
java·开发语言·数据结构
鑫鑫向栄10 小时前
[蓝桥杯]堆的计数
数据结构·c++·算法·蓝桥杯·动态规划
weixin_4196583113 小时前
数据结构之LinkedList
数据结构
无敌的小笼包18 小时前
第四讲:类和对象(下)
数据结构·c++
鑫鑫向栄18 小时前
[蓝桥杯]解谜游戏
数据结构·c++·算法·职场和发展·蓝桥杯