[leetcode]19. Remove Nth Node From End of List删除链表倒数第N个节点
2024-10-18 23:25:39
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;
}
}
最新文章
- python 多进程使用总结
- 2.7我们的第一个Java程序
- react native 环境配置
- haxe jni调用输入法
- DOCTYPE声明作用及用法详解
- Windows Driver Frameworks
- sql server 写性能优化
- 【转】基于laravel制作APP接口(API)
- C语言sizeof
- Dapper连接Oracle
- chrome、safari中的input或textarea
- PAT 团体程序设计天梯赛-练习集 L1-005. 考试座位号
- C++学习日记(二)————初始字符串类型
- Eclipse+Spring+SpringMVC+Maven+Mybatis+MySQL+Tomcat项目搭建
- 利用Tkinter和matplotlib两种方式画饼状图
- 使用websocket实现在线聊天功能
- PyTorch官方中文文档:torch.nn
- svn初涉及使用
- docker--容器和镜像的导入导出及部署
- 论Object.keys(), Object.getOwnPropertyNames(), for in, Object.getOwnPropertySymbol()区别
热门文章
- Linux系统安装管理
- Head First 设计模式 (Eric Freeman / Elisabeth Freeman / Kathy Sierra / Bert Bates 著)
- 第3章 Java数组(上): 一维数组和二维数组
- php正则判断是否同时有数字和字母
- js 遍历EL表达式 list对象
- easyui-datebox 点击事件
- Oracle DBA最常用的269条命令
- 黄聪:通过 itms:services://? 在线安装ipa ,跨过appstore
- IIS 7.0的集成模式和经典模式
- 关于mariad&;mysql部分