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后,将其释放,但是这里我忘了

相关推荐
阿让啊1 小时前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
এ᭄画画的北北1 小时前
力扣-160.相交链表
算法·leetcode·链表
草莓啵啵~1 小时前
搜索二叉树-key的搜索模型
数据结构·c++
丶Darling.2 小时前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
我也不曾来过13 小时前
list底层原理
数据结构·c++·list
mit6.8244 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify4 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .5 小时前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法
egoist20235 小时前
【C++指南】告别C字符串陷阱:如何实现封装string?
开发语言·数据结构·c++·c++11·string·auto·深/浅拷贝
Gsen28196 小时前
AI大模型从0到1记录学习 数据结构和算法 day20
数据结构·学习·算法·生成对抗网络·目标跟踪·语言模型·知识图谱