当前位置:网站首页>[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;
}
};
边栏推荐
- Use of lists
- Cannot change version of project facet Dynamic Web Module to 2.3.
- JS正则表达式基础知识学习
- RT thread API reference manual
- ESP学习问题记录
- 荣耀Magic 3Pro 充电架构分析
- (五)R语言入门生物信息学——ORF和序列分析
- Arm pc=pc+8 is the most understandable explanation
- I2C bus timing explanation
- Feature of sklearn_ extraction. text. CountVectorizer / TfidVectorizer
猜你喜欢
基于Redis的分布式ID生成器
Arduino uno R3 register writing method (1) -- pin level state change
Kconfig Kbuild
【ESP32学习-2】esp32地址映射
Navigator object (determine browser type)
Characteristics, task status and startup of UCOS III
Unit test - unittest framework
Several declarations about pointers [C language]
[Red Treasure Book Notes simplified version] Chapter 12 BOM
Postman 中级使用教程【环境变量、测试脚本、断言、接口文档等】
随机推荐
Basic operations of databases and tables ----- modifying data tables
[esp32 learning-1] construction of Arduino esp32 development environment
[Red Treasure Book Notes simplified version] Chapter 12 BOM
Classification, understanding and application of common methods of JS array
Characteristics, task status and startup of UCOS III
Rough analysis of map file
Gateway fails to route according to the service name, and reports an error service unavailable, status=503
Reno7 60W super flash charging architecture
Missing value filling in data analysis (focus on multiple interpolation method, miseforest)
gcc 编译选项
The first simple case of GNN: Cora classification
Vscode basic configuration
Redis based distributed ID generator
Selective sorting and bubble sorting [C language]
Time slice polling scheduling of RT thread threads
JS object and event learning notes
. elf . map . list . Hex file
Stm32f1+bc20+mqtt+freertos system is connected to Alibaba cloud to transmit temperature and humidity and control LED lights
ES6 grammar summary -- Part I (basic)
@Autowired 和 @Resource 的区别