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

相关推荐
POLITE315 分钟前
Leetcode 21.合并两个有序链表 JavaScript (Day 10)
javascript·leetcode·链表
梭七y38 分钟前
【力扣hot100题】(105)三数之和
数据结构·算法·leetcode
cpp_25014 小时前
P8597 [蓝桥杯 2013 省 B] 翻硬币
数据结构·c++·算法·蓝桥杯·题解
郝学胜-神的一滴5 小时前
Python类型检查之isinstance与type:继承之辨与魔法之道
开发语言·数据结构·python·程序人生
不忘不弃5 小时前
把IP地址转换为字符串
数据结构·tcp/ip·算法
发疯幼稚鬼5 小时前
网络流问题与最小生成树
c语言·网络·数据结构·算法·拓扑学
leoufung5 小时前
LeetCode 63:Unique Paths II - 带障碍网格路径问题的完整解析与面试技巧
算法·leetcode·面试
还不秃顶的计科生5 小时前
力扣hot100第三题:最长连续序列python
python·算法·leetcode
wen__xvn6 小时前
代码随想录算法训练营DAY3第一章 数组part02
java·数据结构·算法