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

相关推荐
中草药z21 分钟前
【Java算法】二分查找 上
数据结构·笔记·算法·leetcode·二分查找·学习方法
努力学习的小廉30 分钟前
双向链表 -- 详细理解和实现
数据结构·链表
m0_5719575843 分钟前
Java | Leetcode Java题解之第219题存在重复元素II
java·leetcode·题解
Mopes__1 小时前
Python | Leetcode Python题解之第220题存在重复元素III
python·leetcode·题解
Miracle_86.1 小时前
【数据结构】单链表:数据结构中的舞者,穿梭于理论与实践的舞池
c语言·数据结构·链表·学习方法
DdddJMs__1351 小时前
C语言 | Leetcode C语言题解之第220题存在重复元素III
c语言·leetcode·题解
m0_571957582 小时前
Java | Leetcode Java题解之第218题天际线问题
java·leetcode·题解
DdddJMs__1352 小时前
C语言 | Leetcode C语言题解之第211题添加与搜索单词-数据结构设计
c语言·leetcode·题解
OYYHXPJR2 小时前
算法重新刷题
数据结构·算法
摸鱼的快乐你不懂3 小时前
金银铜牌排序【二维数组借用Arrays.sort方法进行排序】
数据结构