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

相关推荐
圣保罗的大教堂4 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
晊晌_h5 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦6 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
lisin-lee-cooper11 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-11 小时前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法
带多刺的玫瑰12 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂12 小时前
leetcode 877. 石子游戏 中等
leetcode
哭泣方源炼蛊13 小时前
并查集进阶 P1(带权并查集,并查集分类)
数据结构·c++·算法·二进制·带权并查集
shehuiyuelaiyuehao14 小时前
算法32,连续数组,前缀和+哈希表
算法·leetcode·职场和发展
五_谷_丰_登14 小时前
平衡二叉树(AVL)讲解二
数据结构·c++