leetcode 19. Remove Nth Node From End of List-移除链表元素|双指针
来源:互联网 发布:移动互联网 数据 编辑:程序博客网 时间:2024/05/16 11:29
原题链接:19. Remove Nth Node From End of List
【思路】
如果移除正数第 n 个很容易,可是换做倒数第 n 个就变得有些挠头了。开始时候想着先遍历一遍,数出链表长度 m,然后在第 m - n + 1出做移除操作,可是题目要求只遍历一遍,那么这种思路肯定就要被 pass 了。我们需要换一种思路:
1. 声明两个指针fast 和 slow(假设都指向头结点,但是这个假设后面将会被推翻)
2. 先让 fast 移动 n 步
3. 然后 fast 和 slow 同时移动,直到 fast 指向空(即尾节点的下一个节点)
那么 slow 和尾节点的距离不就是 n 了吗?但是,显然上述思路还存在漏洞,我们必须要在使得 slow 处于倒数 n + 1 个位置才能将倒数第 n 个节点移除。很明显的一个特例我们可以假设刚好要将头结点移除(即长度为 n 的链表移除倒数第 n 个节点),为此我们需要申请一个新的节点 dummyHead 它的下一个节点指向 head:
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummyHead = new ListNode(0), slow = dummyHead, fast = head; dummyHead.next = head; for (int i = 0; i < n; i++) fast = fast.next; while (fast != null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return dummyHead.next; }207 / 207 test cases passed. Runtime: 1 ms Your runtime beats 7.54% of javasubmissions.
1 0
- leetcode 19. Remove Nth Node From End of List-移除链表元素|双指针
- *LeetCode Remove Nth Node From End of List 双指针
- Remove Nth Node From End of List --移除链表中的倒数第k个元素
- leetcode 3. 移除链表的倒数第n个节点 Remove Nth Node From End of List
- LeetCode--Remove Nth Node From End of List(移除链表的倒数第N个节点)Python
- Remove Nth Node From End of List "移除链表中的倒数第N项"
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- leetcode 19. Remove Nth Node From End of List 双指针 + 移动窗口
- 19. Remove Nth Node From End of List leetcode list
- LeetCode-19 Remove Nth Node From End of List(移除尾部第N个节点)
- LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点
- 19. Remove Nth Node From End of List (移除链表倒数第n个节点)
- 19. Remove Nth Node From End of List(移除链表的倒数第n个节点)
- 19. Remove Nth Node From End of List & 快慢指针
- Leetcode #19. Remove Nth Node From End of List 移除倒数第N个链表节点 解题小节
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Linux系统启动过程分析
- VS2013环境下调用winsock会出现的几个小问题
- 模板Trait 技术与简述template 元编程
- 怎样增强MyEclipse的智能提示功能
- Dissecting the Camera Matrix
- leetcode 19. Remove Nth Node From End of List-移除链表元素|双指针
- 绑定服务学习
- Android LayoutInflater详解
- n皇后问题<dfs>
- 图片中的exif数据
- 记一下“树莓派3”
- Android-Service的用法
- 淘宝购物倒计时
- C++第五次实验——数组分离