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

相关推荐
AI情绪识别开源1 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
伟大的车尔尼7 小时前
贪心的概念
数据结构·算法·贪心
AI情绪识别开源7 小时前
检信AI高一分班分科智选评估系统 v2.0测试报告
开发语言·数据结构·人工智能·科技
CoderYanger8 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
雪碧聊技术9 小时前
KMP算法详解
数据结构
Navigator_Z10 小时前
LeetCode //C - 1221. Split a String in Balanced Strings
c语言·算法·leetcode
positive_zpc12 小时前
进阶数据结构图——关键路径(四)
数据结构·图论·关键路径
孙克旭_13 小时前
单链表进阶实操:5 道常考面试题详细解析【Java 实现】
java·开发语言·数据结构·单链表
玄昌盛不会编程13 小时前
LeetCode——2091. 从数组中移除最大值和最小值
java·算法·leetcode
Chester_199913 小时前
CSP202206C.角色授权
开发语言·数据结构·c++·蓝桥杯