[Leetcode] remove nth node from the end of list 删除链表倒数第n各节点
2024-08-27 23:05:27
Given a linked list, remove the n th node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
这题比较简单,使用快慢指针,找到倒数第n个结点的前驱即可,然后连接其前驱和后继即可,值得注意的是,两个while的条件之间的关系。代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n)
{
ListNode *nList=new ListNode(-);
nList->next=head;
ListNode *pre=nList;
ListNode *fast=head;
ListNode *slow=head;
int num=; while(num++<n)
{
fast=fast->next;
}
while(fast->next)
{
pre=pre->next;
slow=slow->next;
fast=fast->next;
}
pre->next=slow->next; return nList->next;
}
};
最新文章
- 去IOE的一点反对意见以及其他
- CentOS配置本地光盘yum源
- IIS 301 重定向 带参数链接
- 336-Palindrome Pairs
- 学习Word2vec
- MFC中添加消息响应函数
- android在程序中打开另一个程序
- UCML平台中 如何设置列表单元格中的链接失效
- Understanding GC pauses in JVM, HotSpot&#39;s minor GC.
- hdu 3954 Level up(线段树)
- jquery的校验规则的方法
- C/C++ typedef
- ASP.NET Core 使用 Google 验证码(reCAPTCHA v3)代替传统验证码
- vue实例生命周期详解
- SSM框架整合搭建教程
- 开源词袋模型DBow3原理&;源码(一)整体结构
- linux如何查看端口被哪个进程占用?
- Windows驱动开发之线程与同步事件
- C++官方文档-运算符重载
- maven+tomcat热部署