203. Remove Linked List Elements

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

    /**

    • 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) {
      struct ListNodedummyHead=new ListNode(0,head);
      struct ListNode
      pre=dummyHead;
      while(pre->next!=NULL){
      if(pre->next->val==val){
      pre->next=pre->next->next;
      }else{
      pre=pre->next;
      }
      }
      return dummyHead->next;
      }
      };

注意:

1.其实这道题可以有两种方法去做,第一种是不适用虚拟头节点的,但是这种方法需要分类,一种是删除的节点是头节点的时候,第二种是其他元素,但是这样的话,代码不够简洁。所以采用了虚拟头节点的方式来做

2.C++中应该在用完dummyHead后,将其释放,但是这里我忘了

相关推荐
橘颂TA44 分钟前
【剑斩OFFER】算法的暴力美学——两数之和
数据结构·算法·leetcode·力扣·结构与算法
云里雾里!1 小时前
力扣 268. 缺失数字 ✅ 【位运算(异或)最优解法】深度解析
算法·leetcode
梭七y1 小时前
【力扣hot100题】(122)回文链表
算法·leetcode·链表
tobias.b1 小时前
408真题-2009-7-数据结构-无向连通图性质
数据结构·算法·408考研·408真题·真题解析
阿猿收手吧!2 小时前
【C++】JSON核心数据结构解析及JSONCPP使用
数据结构·c++·json
tobias.b2 小时前
408真题解析-2009-9-数据结构-小根堆-排序
数据结构·408考研·408真题·真题解析
alphaTao2 小时前
LeetCode 每日一题 2025/12/29-2026/1/4
算法·leetcode
ShaderJoy2 小时前
ShaderJoy —— 《对称镜面下的绞肉机》【算法悬疑短文】【Python】
算法·leetcode·面试
有一个好名字2 小时前
力扣-盛最多水的容器
算法·leetcode·职场和发展
D_FW2 小时前
数据结构第二章:线性表
数据结构·算法