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;
}
};

最新文章

  1. 去IOE的一点反对意见以及其他
  2. CentOS配置本地光盘yum源
  3. IIS 301 重定向 带参数链接
  4. 336-Palindrome Pairs
  5. 学习Word2vec
  6. MFC中添加消息响应函数
  7. android在程序中打开另一个程序
  8. UCML平台中 如何设置列表单元格中的链接失效
  9. Understanding GC pauses in JVM, HotSpot&#39;s minor GC.
  10. hdu 3954 Level up(线段树)
  11. jquery的校验规则的方法
  12. C/C++ typedef
  13. ASP.NET Core 使用 Google 验证码(reCAPTCHA v3)代替传统验证码
  14. vue实例生命周期详解
  15. SSM框架整合搭建教程
  16. 开源词袋模型DBow3原理&amp;源码(一)整体结构
  17. linux如何查看端口被哪个进程占用?
  18. Windows驱动开发之线程与同步事件
  19. C++官方文档-运算符重载
  20. maven+tomcat热部署

热门文章

  1. python中的&quot;is&quot;与&quot;==&quot;比较
  2. SQL优化之语句优化
  3. Nodejs 使用 addons 调用c++ 初体验(一)
  4. 05 redis(进阶)
  5. ctf题目writeup(1)
  6. PHP中文乱码分类及解决办法大全
  7. Linux(CentOS)安装Node.JS
  8. C++基础语言知识大汇总(不断更新!!!)
  9. HI2115软件开发板V150版本AT+NSOST指令
  10. 根据STATUS信息对MySQL进行优化