闯关leetcode——203. Remove Linked List Elements

大纲

题目

地址

https://leetcode.com/problems/remove-linked-list-elements/description/

内容

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6

Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1

Output: []

Example 3:

Input: head = [7,7,7,7], val = 7

Output: []

Constraints:

  • The number of nodes in the list is in the range [0, 104].
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

解题

这题就是要求在单向链表中删除给定值的元素,然后返回新的链表头结点。

思路就是寻找节点(cur)后第一个不是给定值的节点(checkNode),然后让(cur的)next指针指向它(checkNode)。之后对找到的新节点继续做此类处理。

cpp 复制代码
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) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* cur = dummy;
        while (cur != nullptr && cur->next != nullptr) {
            ListNode* checkNode = cur->next;
            while (checkNode != nullptr && checkNode->val == val) {
                checkNode = checkNode->next;
            }
            cur->next = checkNode;
            cur = checkNode;
        }
        return dummy->next;
    }
};

代码地址

https://github.com/f304646673/leetcode/blob/main/203-Remove-Linked-List-Elements/cplusplus/src/solution.hpp

相关推荐
七颗糖很甜6 分钟前
基于 OpenCV 的 FY2 云顶图云块追踪算法实现
人工智能·opencv·算法
__Wedream__7 分钟前
NTIRE 2026 Challenge on Efficient Super-Resolution——冠军方案解读
人工智能·深度学习·算法·计算机视觉·超分辨率重建
FL162386312910 分钟前
基于深度学习mediape实现人员跌倒人体姿势跌倒检测算法源码+说明文件
人工智能·深度学习·算法
wangwangmoon_light11 分钟前
1.23 LeetCode总结(树)_一般树
算法·leetcode·职场和发展
被考核重击13 分钟前
基础算法学习
学习·算法
小O的算法实验室16 分钟前
2026年ASOC,学习驱动人工蜂群算法+移动机器人多目标路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
学传打活20 分钟前
古代汉语是源,现代汉语是流,源与流一脉相承。
微信公众平台·1024程序员节·汉字·中华文化
wfbcg30 分钟前
每日算法练习:LeetCode 30. 串联所有单词的子串 ✅
算法·leetcode·职场和发展
玉树临风ives34 分钟前
atcoder ABC 453 题解
数据结构·c++·算法·图论·atcoder
田梓燊40 分钟前
leetcode 48
算法·leetcode·职场和发展