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

相关推荐
时针滴滴答啊3 小时前
最大子数组和
算法·leetcode·职场和发展
疯狂打码的少年5 小时前
【数据结构】交换类排序:冒泡与快速排序
数据结构·笔记·算法·排序算法
Nil2086 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
hn小菜鸡6 小时前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
疯狂打码的少年7 小时前
【数据结构】哈希表:构造与冲突处理
数据结构·笔记·哈希算法·散列表
土司大王8 小时前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王8 小时前
LeetCode hot100——回文链表
算法·leetcode·链表
淡海水8 小时前
03-02-线性-List-T-动态数组布局-扩容与操作成本
数据结构·windows·c#·list·编译·clr·机器码
evans在进步9 小时前
LeetCode 1143:最长公共子序列——Java 二维动态规划详解
java·leetcode·动态规划
小飞学编程...17 小时前
【哈希表】
数据结构·哈希算法·散列表