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

相关推荐
ChinaRainbowSea1 小时前
MySQL 索引的数据结构(详细说明)
java·数据结构·数据库·后端·mysql
白晨并不是很能熬夜2 小时前
【JVM】字节码指令集
java·开发语言·汇编·jvm·数据结构·后端·javac
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧2 小时前
C语言_数据结构总结7:顺序队列(循环队列)
c语言·开发语言·数据结构·算法·visualstudio·visual studio
橘颂TA2 小时前
每日一练之合并两个有序链表
数据结构·链表
LIUJH12332 小时前
数据结构——单调栈
开发语言·数据结构·c++·算法
2301_807449202 小时前
字符串相乘——力扣
java·算法·leetcode
shylyly_3 小时前
list的模拟实现
数据结构·c++·链表·迭代器·list·list的模拟实现
yadanuof3 小时前
leetcode hot100 图论
leetcode·深度优先·图论
ianozo3 小时前
数据结构--【栈与队列】笔记
数据结构·笔记
xiao--xin4 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法