Given a linked list, remove the n-th node from the end of list and return its head.

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.

Follow up:

Could you do this in one pass?

题意: 删除链表倒数第N个节点

Solution1: Two Pointers(fast and slow)

1. Let fast pointer to move n steps in advance, making sure there is n steps gap between fast and slow

2. Move fast and slow pointer together until fast.next == null

code

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/ /*
Time: O(n)
Space: O(1)
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy, fast = dummy; for (int i = 0; i < n; i++) // fast先走n步
fast = fast.next; while(fast.next != null) { // fast和slow一起走
slow = slow.next;
fast = fast.next;
}
//直接skip要删除的节点
slow.next = slow.next.next; // 思考为何不能写成 slow.next = fast;
return dummy.next;
}
}

最新文章

  1. python 多进程使用总结
  2. 2.7我们的第一个Java程序
  3. react native 环境配置
  4. haxe jni调用输入法
  5. DOCTYPE声明作用及用法详解
  6. Windows Driver Frameworks
  7. sql server 写性能优化
  8. 【转】基于laravel制作APP接口(API)
  9. C语言sizeof
  10. Dapper连接Oracle
  11. chrome、safari中的input或textarea
  12. PAT 团体程序设计天梯赛-练习集 L1-005. 考试座位号
  13. C++学习日记(二)————初始字符串类型
  14. Eclipse+Spring+SpringMVC+Maven+Mybatis+MySQL+Tomcat项目搭建
  15. 利用Tkinter和matplotlib两种方式画饼状图
  16. 使用websocket实现在线聊天功能
  17. PyTorch官方中文文档:torch.nn
  18. svn初涉及使用
  19. docker--容器和镜像的导入导出及部署
  20. 论Object.keys(), Object.getOwnPropertyNames(), for in, Object.getOwnPropertySymbol()区别

热门文章

  1. Linux系统安装管理
  2. Head First 设计模式 (Eric Freeman / Elisabeth Freeman / Kathy Sierra / Bert Bates 著)
  3. 第3章 Java数组(上): 一维数组和二维数组
  4. php正则判断是否同时有数字和字母
  5. js 遍历EL表达式 list对象
  6. easyui-datebox 点击事件
  7. Oracle DBA最常用的269条命令
  8. 黄聪:通过 itms:services://? 在线安装ipa ,跨过appstore
  9. IIS 7.0的集成模式和经典模式
  10. 关于mariad&amp;mysql部分