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;

        
    }
};
相关推荐
why1519 小时前
面经整理——算法
java·数据结构·算法
鹿角片ljp11 小时前
力扣140.快慢指针法求解链表倒数第K个节点
算法·leetcode·链表
List<String> error_P12 小时前
数据结构:链表-单向链表篇
算法·链表
曾几何时`12 小时前
归并排序(一)
数据结构·算法·leetcode
业精于勤的牙14 小时前
小张刷题计划(二)
数据结构·算法
亮子AI15 小时前
【Tiptap】如何使用 ordered list?
数据结构·list·tiptap
南莺莺15 小时前
二叉排序树的创建和基本操作---C++实现
数据结构·c++·算法··二叉排序树
仰泳的熊猫15 小时前
1061 Dating
数据结构·c++·算法·pat考试
Fcy64815 小时前
二叉搜索树(C++实现)
开发语言·数据结构·c++·二叉搜索树
CoderYanger15 小时前
A.每日一题——1523. 在区间范围内统计奇数数目
java·数据结构·算法·leetcode·职场和发展