当前位置: 首页 > news >正文

leetcode之移除链表的元素

题目描述

删除链表中等于给定值 val 的所有节点。

示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

题目分析

这里一共两种思路。
第一种思路是建立一个ListNode *cur,这个cur比head慢一步,这样,两个节点同时向前走,当head节点找到val后,这时cur->next=head->next。

第二种思路是将这样的删除运算改成递归运算。

第一种思路源代码:

ListNode* removeElements(ListNode* head, int val) {ListNode *cur = new ListNode(-1);ListNode *dummpy = cur;while(head!=NULL){if(head->val==val){cur->next=head->next;}else{cur->next=head;cur=cur->next;}head=head->next;}return dummpy->next;}

第二种思路源代码:

if (head == null) return null;head.next = removeElements(head.next, val);return head.val == val ? head.next : head;

http://www.taodudu.cc/news/show-1782113.html

相关文章:

  • 【physx/wasm】在physx中添加自定义接口并重新编译wasm
  • excel---常用操作
  • Lora训练Windows[笔记]
  • linux基础指令讲解(ls、pwd、cd、touch、mkdir)
  • InnoDB 事务处理机制
  • 启明云端ESP32 C3 模组WT32C3通过 MQTT 连接 AWS
  • leetcode之奇偶链表
  • leetcode之回文链表
  • ubuntu16.04下安装配置caffe2和detectron(亲测有效,非常简单)
  • leetcode之字符串中的第一个唯一字符
  • 哈希表中处理冲突的方法
  • SENet算法解析
  • SNIP物体检测算法理解
  • yolov3聚类自己数据的anchor box
  • Ubuntu下安装qt57creator-plugin-ros,在QT中进行ROS开发(亲测有效)
  • ROS下面调用自定义的头文件和.cpp/.so文件(亲测有效)
  • C++调用编译好的darknet来进行物体监测
  • hard-negative mining详细介绍
  • yolov3中如何进行聚类得到anchor box的
  • ubuntu16.04下编译安装Autoware
  • catkin_make和cmake
  • 深度学习三种分割定义
  • 基于激光雷达点云数据的目标检测
  • 递归和循环两种方式求解连续数的相加
  • PCL中把txt文件转换成.pcd文件(很简单)
  • pcl对点云进行直通滤波
  • error: (-205:Formats of input arguments do not match) All the matrices must have the same data type
  • ubuntu16.04下Qt无法输入中文注释
  • ROS下sensor_msgs::ImagePtr到sensor_msgs::Image之间的转换
  • ROS下同时接收多个话题并实现相机和雷达的数据融合
  • 柱状图之最大矩形面积
  • 哈希函数的构造方法以及哈希表解决冲突的方式
  • 回旋镖的数量
  • 伪代码之KMeans和DBSCAN
  • leetcode之有效的括号
  • leetcode之每日温度