当前位置:网站首页>[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占用内存过大解决方案
- ES6语法总结--上篇(基础篇)
- [esp32 learning-1] construction of Arduino esp32 development environment
- 高通&MTK&麒麟 手机平台USB3.0方案对比
- ES6 grammar summary -- Part I (basic)
- I2C bus timing explanation
- MySQL takes up too much memory solution
- ESP learning problem record
- 2022.2.12 resumption
- Several declarations about pointers [C language]
猜你喜欢

ORA-02030: can only select from fixed tables/views

ESP learning problem record

基于Redis的分布式锁 以及 超详细的改进思路
![[Red Treasure Book Notes simplified version] Chapter 12 BOM](/img/ff/0ad410b5b556c0e16a4076a2a0577b.jpg)
[Red Treasure Book Notes simplified version] Chapter 12 BOM

Pytorch: tensor operation (I) contiguous

JS数组常用方法的分类、理解和运用

JS Title: input array, exchange the largest with the first element, exchange the smallest with the last element, and output array.

arduino JSON数据信息解析

Pytorch four commonly used optimizer tests

AMBA、AHB、APB、AXI的理解
随机推荐
列表的使用
基於Redis的分布式ID生成器
open-mmlab labelImg mmdetection
Variable parameter principle of C language function: VA_ start、va_ Arg and VA_ end
vim命令行笔记
STM32 how to locate the code segment that causes hard fault
MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解
Comparaison des solutions pour la plate - forme mobile Qualcomm & MTK & Kirin USB 3.0
OPPO VOOC快充电路和协议
C language callback function [C language]
单片机蓝牙无线烧录
Basic operations of databases and tables ----- creating data tables
Characteristics, task status and startup of UCOS III
Pytoch temperature prediction
arduino获取数组的长度
Fashion-Gen: The Generative Fashion Dataset and Challenge 论文解读&数据集介绍
高通&MTK&麒麟 手机平台USB3.0方案对比
MySQL time, time zone, auto fill 0
GCC compilation options
JS function promotion and declaration promotion of VaR variable