当前位置:网站首页>[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;
}
}
};
边栏推荐
- .elf .map .list .hex文件
- 小天才电话手表 Z3工作原理
- Cannot change version of project facet Dynamic Web Module to 2.3.
- Symbolic representation of functions in deep learning papers
- Navigator object (determine browser type)
- Redis based distributed locks and ultra detailed improvement ideas
- Several declarations about pointers [C language]
- RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED
- 嵌入式启动流程
- . elf . map . list . Hex file
猜你喜欢

Custom view puzzle getcolor r.color The color obtained by colorprimary is incorrect

ES6语法总结--上篇(基础篇)

Feature of sklearn_ extraction. text. CountVectorizer / TfidVectorizer

CUDA C programming authoritative guide Grossman Chapter 4 global memory

JS variable types and common type conversions

Pytorch four commonly used optimizer tests

單片機藍牙無線燒錄

Common properties of location

MySQL time, time zone, auto fill 0

(四)R语言的数据可视化——矩阵图、柱状图、饼图、散点图与线性回归、带状图
随机推荐
Générateur d'identification distribué basé sur redis
(四)R语言的数据可视化——矩阵图、柱状图、饼图、散点图与线性回归、带状图
The dolphin scheduler remotely executes shell scripts through the expect command
gcc 编译选项
Types de variables JS et transformations de type communes
基于Redis的分布式锁 以及 超详细的改进思路
VSCode基础配置
JS数组常用方法的分类、理解和运用
js题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
Minio文件下载问题——inputstream:closed
Detailed explanation of truncate usage
MySQL takes up too much memory solution
Custom view puzzle getcolor r.color The color obtained by colorprimary is incorrect
Rough analysis of map file
嵌入式启动流程
arduino JSON数据信息解析
基於Redis的分布式ID生成器
Several declarations about pointers [C language]
单片机蓝牙无线烧录
Inline detailed explanation [C language]