当前位置:网站首页>[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;
}
}
};
边栏推荐
- Dead loop in FreeRTOS task function
- Cannot change version of project facet Dynamic Web Module to 2.3.
- Générateur d'identification distribué basé sur redis
- CUDA C programming authoritative guide Grossman Chapter 4 global memory
- Basic operations of databases and tables ----- creating data tables
- Whistle+switchyomega configure web proxy
- Mysqldump error1066 error solution
- MySQL占用内存过大解决方案
- ESP8266使用arduino连接阿里云物联网
- Classification, understanding and application of common methods of JS array
猜你喜欢
Comparaison des solutions pour la plate - forme mobile Qualcomm & MTK & Kirin USB 3.0
ESP8266连接onenet(旧版MQTT方式)
ES6 grammar summary -- Part 2 (advanced part es6~es11)
Characteristics, task status and startup of UCOS III
arduino UNO R3的寄存器写法(1)-----引脚电平状态变化
Feature of sklearn_ extraction. text. CountVectorizer / TfidVectorizer
记一次云服务器被密码爆破的经历——关小黑屋、改密码、改端口
Analysis of charging architecture of glory magic 3pro
[golang] leetcode intermediate - fill in the next right node pointer of each node & the k-smallest element in the binary search tree
open-mmlab labelImg mmdetection
随机推荐
Redis based distributed locks and ultra detailed improvement ideas
imgcat使用心得
ES6 grammar summary -- Part 2 (advanced part es6~es11)
AMBA、AHB、APB、AXI的理解
Comparison of solutions of Qualcomm & MTK & Kirin mobile platform USB3.0
Unit test - unittest framework
VSCode基础配置
Pat 1097 duplication on a linked list (25 points)
(三)R语言的生物信息学入门——Function, data.frame, 简单DNA读取与分析
Talking about the startup of Oracle Database
MySQL時間、時區、自動填充0的問題
Gateway fails to route according to the service name, and reports an error service unavailable, status=503
Use of lists
Keyword inline (inline function) usage analysis [C language]
OSPF message details - LSA overview
ES6 grammar summary -- Part I (basic)
ORA-02030: can only select from fixed tables/views
2022.2.12 resumption
(一)R语言入门指南——数据分析的第一步
单片机蓝牙无线烧录