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 小时前
力扣343 整数拆分
数据结构·算法·leetcode
Heartoxx2 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼3 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
学不动CV了12 小时前
数据结构---线性表理解(一)
数据结构
ysa05103013 小时前
数论基础知识和模板
数据结构·c++·笔记·算法
今天背单词了吗98013 小时前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法
气质、小青年!13 小时前
【排序算法】
c语言·数据结构
clock的时钟15 小时前
暑期数据结构第一天
数据结构·算法
小小小小王王王16 小时前
求猪肉价格最大值
数据结构·c++·算法
SuperW18 小时前
数据结构——队列
数据结构