闯关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, 10^4^.
  • 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

相关推荐
小O的算法实验室1 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
Tbisnic2 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx2 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归3 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing4 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习4 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨4 小时前
基础数论总结
笔记·学习·算法
夜不会漫长6 小时前
C++入门(1)
开发语言·c++·算法
wen_zhufeng7 小时前
IndexTTS 2.5 技术报告
人工智能·算法·机器学习
大熊背7 小时前
树莓派相机自动白平衡详解(四)
算法·树莓派·白平衡·isppipeline