Leetcode -- Remove Nth Node From End of List
来源:互联网 发布:88端口怎么起 编辑:程序博客网 时间:2024/05/20 11:31
问题链接:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
问题描述:
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.
API:public ListNode removeNthFromEnd(ListNode head, int n)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
问题分析:本题实际上就是Find Nth node from end of list的翻版。只是因为需要remove又只能扫一遍,所以会多出一些边界问题
首先介绍一下Find nth node from end of list的做法。
本质上这题就是双指针问题,以后在linkedlist的问题里也会遇到一些双指针的问题。
第一步是定义一个快指针找到第n + 1个指针,譬如说在上述例子里,先找到3。
然后再定义一个慢指针指向头指针,然后快慢同时往下扫,当快指针走到了尽头空指针的时候,慢指针就会指向nth node from end of list.
理论就是这样的,慢指针和快指针之间的差是n。所以当快指针走到尽头end的时候,慢指针自然就是nth node from end of list.
但事实上本题是要remove,而且只能扫一遍,所以本质上是要找n + 1th node from end of list.但之前我们提到了边界问题,这个边界问题就是当要删除头指针的时候,你是没有头指针之前的那个指针的。所以在快指针扫的时候,我们就要做一个特殊判断,也就是当快指针在第一次走的时候已经指向null了,我们就可以直接删除头指针了。也就是直接返回头指针下面那个指针。
给出代码如下:
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode tmp = head; while(n >= 0){ if(tmp == null) return head.next; n--; tmp = tmp.next; } ListNode prev = head; while(tmp != null){ prev = prev.next; tmp = tmp.next; } prev.next = prev.next.next; return head; }
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- Servlet中filter过滤<dispatcher>FORWARD</dispatcher>标签使用
- glViewport
- linux服务器切换用户只显示-bash-4.1#不显示路径
- RankLib源码分析---MART(GBRT)
- 二叉查找树、红黑树、B树、B+树、AVL树
- Leetcode -- Remove Nth Node From End of List
- OpenGL 房子
- table的HTML5+css3的可用样式
- 浅析UML建模中的几种关系
- CM开发日志 - 搜索引擎(三)
- javascript:void(0)是什么意思?JS的几种跳转
- 密码学概述
- libsvm使用
- R语言:多元线性回归和模型检验