Given a linked list, remove the nth 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个节点,限定n一定是有效的,即n不会大于链表中的元素总数。还有题目要求一次遍历解决问题,那么就得想些比较巧妙的方法了。比如首先要考虑的时,如何找到倒数第N个节点,由于只允许一次遍历,所以不能用一次完整的遍历来统计链表中元素的个数,而是遍历到对应位置就应该移除了。那么就需要用两个指针来帮助解题,pre 和 cur 指针。首先 cur 指针先向前走N步,如果此时 cur 指向空,说明N为链表的长度,则需要移除的为首元素,那么此时返回 head->next 即可,如果 cur 存在,再继续往下走,此时 pre 指针也跟着走,直到 cur 为最后一个元素时停止,此时 pre 指向要移除元素的前一个元素,再修改指针跳过需要移除的元素即可,参见代码如下:

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head->next) return NULL;
ListNode *pre = head, *cur = head;
for (int i = ; i < n; ++i) cur = cur->next;
if (!cur) return head->next;
while (cur->next) {
cur = cur->next;
pre = pre->next;
}
pre->next = pre->next->next;
return head;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/19

类似题目:

Linked List Cycle

Linked List Cycle II

参考资料:

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8812/My-short-C%2B%2B-solution

https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8804/Simple-Java-solution-in-one-pass

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. 关于CommonJS规范摘录
  2. 【Spring-web】RestTemplate源码学习
  3. JArray数组每个JObject对象添加一个键值对
  4. iOS开发——源代码管理——git(分布式版本控制和集中式版本控制对比,git和SVN对比,git常用指令,搭建GitHub远程仓库,搭建oschina远程仓库 )
  5. MONO 说谈
  6. include动作标记和include指令标记学习笔记
  7. 在EF的code frist下写稳健的权限管理系统:MVC过滤拦截,权限核心(五)
  8. PHP类中的__get()和__set函数到底有什么用?
  9. 零基础学习云计算及大数据DBA集群架构师【预科2015年12月14日周一】
  10. 使用 CodeIgniter 框架快速开发 PHP 应用(四)
  11. 嵌套for in循环组合cat方式文件中包含空格问题
  12. python的切片操作
  13. PHPstorm 2017激活
  14. python之路--内置函数03
  15. Redis + keepalived 高可用行配置检测脚本
  16. nginx使用https协议
  17. python----常用模块(random,string,time&amp;datetime,os,sys,xpinyin(拼音))
  18. SpringBoot 调用 mysql存储过程的实战
  19. 2017上海C++面试
  20. recv用TCP和TUDP下的区别

热门文章

  1. pixijs shader 扫光加强版
  2. Autoware 培训笔记 No. 1——构建点云地图
  3. 关于 Scrapy 中自定义 Spider 传递参数问题
  4. 用ASP.NET创建数据库
  5. C++调用linux命令并获取返回值
  6. 面试前必须要知道的21道Redis面试题
  7. flask-script、flask-admin组件
  8. Python分页
  9. python网络编程-2
  10. wpf DATAgrid模板中button 命令绑定以及命令参数绑定