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 小时前
[数据结构]:5.二叉树链式结构的实现1
数据结构
青桔柠薯片3 小时前
数据结构:单向链表,顺序栈和链式栈
数据结构·链表
XiaoFan0124 小时前
将有向工作流图转为结构树的实现
java·数据结构·决策树
睡一觉就好了。4 小时前
快速排序——霍尔排序,前后指针排序,非递归排序
数据结构·算法·排序算法
齐落山大勇4 小时前
数据结构——单链表
数据结构
皮皮哎哟5 小时前
深入浅出双向链表与Linux内核链表 附数组链表核心区别解析
c语言·数据结构·内核链表·双向链表·循环链表·数组和链表的区别
wWYy.6 小时前
指针与引用区别
数据结构
VT.馒头6 小时前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
历程里程碑6 小时前
Linux 17 程序地址空间
linux·运维·服务器·开发语言·数据结构·笔记·排序算法
-dzk-6 小时前
【代码随想录】LC 203.移除链表元素
c语言·数据结构·c++·算法·链表