当前位置:网站首页>[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;
}
}
};
边栏推荐
- Symbolic representation of functions in deep learning papers
- Gateway 根据服务名路由失败,报错 Service Unavailable, status=503
- Custom view puzzle getcolor r.color The color obtained by colorprimary is incorrect
- Who says that PT online schema change does not lock the table, or deadlock
- . elf . map . list . Hex file
- Several declarations about pointers [C language]
- Pytoch temperature prediction
- Arduino JSON data information parsing
- GCC compilation options
- [golang] leetcode intermediate - fill in the next right node pointer of each node & the k-smallest element in the binary search tree
猜你喜欢

OPPO VOOC快充电路和协议

基于Redis的分布式ID生成器

Oppo vooc fast charging circuit and protocol

ES6 grammar summary -- Part I (basic)

MySQL time, time zone, auto fill 0

js题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

记一次云服务器被密码爆破的经历——关小黑屋、改密码、改端口

Redis cache update strategy, cache penetration, avalanche, breakdown problems

I2C bus timing explanation

Fashion-Gen: The Generative Fashion Dataset and Challenge 论文解读&数据集介绍
随机推荐
Arduino gets the length of the array
关于Gateway中使用@Controller的问题
vim命令行笔记
MySQL時間、時區、自動填充0的問題
JS regular expression basic knowledge learning
Types de variables JS et transformations de type communes
JS变量类型以及常用类型转换
.elf .map .list .hex文件
Pytorch: tensor operation (I) contiguous
js 变量作用域和函数的学习笔记
Comparaison des solutions pour la plate - forme mobile Qualcomm & MTK & Kirin USB 3.0
Amba, ahb, APB, Axi Understanding
小天才电话手表 Z3工作原理
Classification, understanding and application of common methods of JS array
Remember an experience of ECS being blown up by passwords - closing a small black house, changing passwords, and changing ports
ES6语法总结--上篇(基础篇)
【ESP32学习-2】esp32地址映射
Page performance optimization of video scene
NRF24L01故障排查
ES6 grammar summary -- Part 2 (advanced part es6~es11)