当前位置:网站首页>[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;
}
};
边栏推荐
- MySQL时间、时区、自动填充0的问题
- Basic operations of databases and tables ----- modifying data tables
- Several declarations about pointers [C language]
- JS variable types and common type conversions
- Programmers can make mistakes. Basic pointers and arrays of C language
- 小天才电话手表 Z3工作原理
- ES6 grammar summary -- Part I (basic)
- Understanding of AMBA, AHB, APB and Axi
- Amba, ahb, APB, Axi Understanding
- Cannot change version of project facet Dynamic Web Module to 2.3.
猜你喜欢
js题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
JS变量类型以及常用类型转换
Walk into WPF's drawing Bing Dwen Dwen
I2C bus timing explanation
Custom view puzzle getcolor r.color The color obtained by colorprimary is incorrect
Vscode basic configuration
Detailed explanation of 5g working principle (explanation & illustration)
Redis based distributed ID generator
A possible cause and solution of "stuck" main thread of RT thread
[esp32 learning-2] esp32 address mapping
随机推荐
Whistle+switchyomega configure web proxy
数据库课程设计:高校教务管理系统(含代码)
Time slice polling scheduling of RT thread threads
By v$rman_ backup_ job_ Oracle "bug" caused by details
ESP learning problem record
嵌入式启动流程
Postman 中级使用教程【环境变量、测试脚本、断言、接口文档等】
【ESP32学习-1】Arduino ESP32开发环境搭建
E-commerce data analysis -- salary prediction (linear regression)
imgcat使用心得
ORA-02030: can only select from fixed tables/views
Inline detailed explanation [C language]
The dolphin scheduler remotely executes shell scripts through the expect command
open-mmlab labelImg mmdetection
JS function promotion and declaration promotion of VaR variable
Kconfig Kbuild
Basic operations of databases and tables ----- creating data tables
.elf .map .list .hex文件
Mysql database interview questions
2022.2.12 resumption