[leetCode]Remove Nth Node From End of List
来源:互联网 发布:网口数据监控软件 编辑:程序博客网 时间:2024/06/06 00:11
题目描述如下:
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.
原本采用的是先遍历一次得到链表的长度,然后根据得到的长度进行二次遍历删除,提交后可以通过,但是没有满足只遍历一次的要求。于是,采用双指针的思想,为了正确定位到要删除的位置,因此,需要前指针start与后指针end的位置相差n,start指向的就是待删除节点的父节点。注意如果是删除头结点时的条件判断。
代码如下:
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null)return head; ListNode start,end; start=new ListNode(-1); start.next=head; end=head; int l=1; for(int i=0;i<n-1;i++){ end=end.next; l++; } while(end.next!=null){ end=end.next; l++; start=start.next; } //System.out.println(l+","+start.val+","+end.val); if(l==n)return head.next; ListNode denode=start.next; start.next=denode.next; return head; }}
0 0
- 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
- 八大内部排序算法(中)-基数排序(java实现)
- Android Vibrate
- 教你快速SDK接入——快速批量修改渠道号
- 欢迎使用CSDN-markdown编辑器
- Matlab 基础
- [leetCode]Remove Nth Node From End of List
- iOS UI学习 自定义View和ViewController
- FIRST集和FOLLOW集
- 求数组中的最大数和最小数
- LeetCode||add Two Numbers
- (创建型模式二)工厂方法模式
- 程序设计语言综合实践 6.1 prime
- hdu 3746 ——Cyclic Nacklace
- Android手机耗电深度解析!