闯关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

相关推荐
Joyner20181 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
因兹菜1 小时前
[LeetCode]day9 203.移除链表元素
算法·leetcode·链表
LNsupermali1 小时前
力扣257. 二叉树的所有路径(遍历思想解决)
算法·leetcode·职场和发展
雾月551 小时前
LeetCode LCR180文件组合
算法·leetcode·职场和发展
萌の鱼1 小时前
leetcode 2080. 区间内查询数字的频率
数据结构·c++·算法·leetcode
Tisfy1 小时前
LeetCode 0541.反转字符串 II:模拟
算法·leetcode·字符串·题解
CM莫问3 小时前
什么是门控循环单元?
人工智能·pytorch·python·rnn·深度学习·算法·gru
查理零世3 小时前
【算法】回溯算法专题① ——子集型回溯 python
python·算法
labmem13 小时前
Leetcode:541
算法·leetcode·职场和发展
某个默默无闻奋斗的人4 小时前
深度优先搜索(DFS)
算法·深度优先