当前位置:网站首页>[leetcode19]删除链表中倒数第n个结点
[leetcode19]删除链表中倒数第n个结点
2022-07-06 09:17:00 【劲腰傩舞】
个人向
前后双指针
题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
/*方法就是定义两个指针。相差间隔恒定为n。并且在一次遍历中同时前进。简称前后双指针*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
/*先定义一个头结点。统一操作。官方的称呼是哑结点,即dummy*/
ListNode* dummy = new ListNode(0, head);
/*定义一前一后两个指针。需要后面的指针比前面的指针多走n+1次 * 因为遍历一遍之后。后指针最终指向null。还需要保证前指针正好指向被删除结点的前驱。*/
/*注意*的优先级高于int,会先结合变量,listnode (*a) */
ListNode* front = dummy, * back = dummy;
for (int i = 1; i <= n + 1; i++)
back = back->next;
while (back) {
front = front->next;
back = back->next;
}
/*删除*/
front->next = front->next->next;
/*别返回head,该指针指向的结点可能已经被删除了*/
/*定义头结点的好处。统一操作。同时可以准确返回第一个结点对应的指针。 *即不用自己单独维护头指针了。两种操作二选一*/
return dummy->next;
}
};
边栏推荐
- AMBA、AHB、APB、AXI的理解
- About using @controller in gateway
- Esp8266 connects to bafayun (TCP maker cloud) through Arduino IED
- Redis based distributed locks and ultra detailed improvement ideas
- Cannot change version of project facet Dynamic Web Module to 2.3.
- (一)R语言入门指南——数据分析的第一步
- ES6 grammar summary -- Part 2 (advanced part es6~es11)
- Esp8266 uses Arduino to connect Alibaba cloud Internet of things
- HCIP Day 12
- Selective sorting and bubble sorting [C language]
猜你喜欢

Arduino uno R3 register writing method (1) -- pin level state change

Kconfig Kbuild

Arm pc=pc+8 is the most understandable explanation

Page performance optimization of video scene

Learning notes of JS variable scope and function

RT thread API reference manual

JS 函数提升和var变量的声明提升

ESP8266使用arduino连接阿里云物联网

JS正则表达式基础知识学习
![[esp32 learning-2] esp32 address mapping](/img/ee/c4aa0f7aed7543bb6807d7fd852c88.png)
[esp32 learning-2] esp32 address mapping
随机推荐
ES6 grammar summary -- Part I (basic)
[golang] leetcode intermediate - fill in the next right node pointer of each node & the k-smallest element in the binary search tree
arduino JSON数据信息解析
JS变量类型以及常用类型转换
ES6 grammar summary -- Part 2 (advanced part es6~es11)
vim命令行笔记
arduino获取随机数
(四)R语言的数据可视化——矩阵图、柱状图、饼图、散点图与线性回归、带状图
JS function promotion and declaration promotion of VaR variable
高通&MTK&麒麟 手機平臺USB3.0方案對比
Pytorch four commonly used optimizer tests
MySQL时间、时区、自动填充0的问题
Detailed explanation of Union [C language]
E-commerce data analysis -- salary prediction (linear regression)
(五)R语言入门生物信息学——ORF和序列分析
MySQL time, time zone, auto fill 0
Basic operations of databases and tables ----- view data tables
ESP learning problem record
Intermediate use tutorial of postman [environment variables, test scripts, assertions, interface documents, etc.]
Oppo vooc fast charging circuit and protocol