当前位置:网站首页>[Offer18]删除链表的节点
[Offer18]删除链表的节点
2022-07-06 09:17:00 【劲腰傩舞】
问题
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
/*返回链表的头指针,要么使用头结点->next实现,要么动态维护头指针。代码选择了第二种*/
ListNode* deleteNode(ListNode* head, int val) {
/*遍历该链表的一个指针*/
ListNode* current = head;
/*删除一个结点的本质是找到其前驱。*/
ListNode* prior = head;
/*没有指定链表的长度。那就一直循环。*/
while (1) {
/*找到结点的情况下*/
if (current->val == val) {
/*上来就直接找到了目标,第一个结点没有前驱。需要特殊处理*/
if (current == head) {
/*第一意识居然是head++,废了*/
head = head->next;
return head;
}
else {
prior->next = current->next;
return head;
}
}
/*没有找到的话,备份一下当前结点*/
prior = current;
current = current->next;
}
}
};
边栏推荐
- ESP learning problem record
- 【ESP32学习-1】Arduino ESP32开发环境搭建
- Comparaison des solutions pour la plate - forme mobile Qualcomm & MTK & Kirin USB 3.0
- NRF24L01故障排查
- Keyword inline (inline function) usage analysis [C language]
- Imgcat usage experience
- Whistle+switchyomega configure web proxy
- Pytorch: tensor operation (I) contiguous
- The first simple case of GNN: Cora classification
- Pytorch four commonly used optimizer tests
猜你喜欢

JS variable types and common type conversions

MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解

Programmers can make mistakes. Basic pointers and arrays of C language

MySQL time, time zone, auto fill 0

Unit test - unittest framework

JS变量类型以及常用类型转换

程序员老鸟都会搞错的问题 C语言基础 指针和数组

(四)R语言的数据可视化——矩阵图、柱状图、饼图、散点图与线性回归、带状图

Basic operations of databases and tables ----- modifying data tables

Understanding of AMBA, AHB, APB and Axi
随机推荐
A possible cause and solution of "stuck" main thread of RT thread
Postman 中级使用教程【环境变量、测试脚本、断言、接口文档等】
Basic knowledge of lithium battery
Esp8266 connects to onenet cloud platform (mqtt) through Arduino IDE
Cannot change version of project facet Dynamic Web Module to 2.3.
Pytoch temperature prediction
ESP学习问题记录
MySQL replacement field part content
@The difference between Autowired and @resource
The first simple case of GNN: Cora classification
Important methods of array and string
NRF24L01故障排查
Missing value filling in data analysis (focus on multiple interpolation method, miseforest)
Talking about the startup of Oracle Database
MySQL時間、時區、自動填充0的問題
Mysql database interview questions
I2C bus timing explanation
Pytorch: tensor operation (I) contiguous
(五)R语言入门生物信息学——ORF和序列分析
History object