当前位置:网站首页>[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;
}
}
};
边栏推荐
- I2C bus timing explanation
- open-mmlab labelImg mmdetection
- Comparaison des solutions pour la plate - forme mobile Qualcomm & MTK & Kirin USB 3.0
- RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED
- Postman 中级使用教程【环境变量、测试脚本、断言、接口文档等】
- Understanding of AMBA, AHB, APB and Axi
- GCC compilation options
- 数据库课程设计:高校教务管理系统(含代码)
- Oppo vooc fast charging circuit and protocol
- Kconfig Kbuild
猜你喜欢
E-commerce data analysis -- salary prediction (linear regression)
Stm32f1+bc20+mqtt+freertos system is connected to Alibaba cloud to transmit temperature and humidity and control LED lights
Redis based distributed locks and ultra detailed improvement ideas
Missing value filling in data analysis (focus on multiple interpolation method, miseforest)
Arm pc=pc+8 is the most understandable explanation
高通&MTK&麒麟 手机平台USB3.0方案对比
Classification, understanding and application of common methods of JS array
(四)R语言的数据可视化——矩阵图、柱状图、饼图、散点图与线性回归、带状图
ES6 grammar summary -- Part I (basic)
History object
随机推荐
NRF24L01故障排查
Learning notes of JS variable scope and function
(五)R语言入门生物信息学——ORF和序列分析
Rough analysis of map file
Common DOS commands
ES6 grammar summary -- Part I (basic)
高通&MTK&麒麟 手機平臺USB3.0方案對比
Detailed explanation of 5g working principle (explanation & illustration)
@The difference between Autowired and @resource
JS 函数提升和var变量的声明提升
C language, log print file name, function name, line number, date and time
【ESP32学习-1】Arduino ESP32开发环境搭建
[golang] leetcode intermediate - fill in the next right node pointer of each node & the k-smallest element in the binary search tree
ESP8266使用arduino连接阿里云物联网
JS object and event learning notes
arduino JSON数据信息解析
Redis based distributed locks and ultra detailed improvement ideas
Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
Redis based distributed ID generator
Kaggle competition two Sigma connect: rental listing inquiries (xgboost)