Remove Nth Node From End of List
来源:互联网 发布:神仙劫坐骑升阶数据 编辑:程序博客网 时间:2024/04/30 12:05
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.
Analysis:
1. The fast pointer points to the nth node after the head first.
2. Both of the fast and slow pointers start to move at the same speed, which is 1 node per time.
3. When the fast pointer points to null, the node pointed by the slow pointer should be the one that needs to be deleted.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode newhead = new ListNode(0); newhead.next = head; ListNode pslow = newhead; ListNode slow = head; ListNode fast = head; if(head == null) return head; for(int i=1; i<=n; i++) { fast = fast.next; } while(fast != null) { pslow = slow; slow = slow.next; fast = fast.next; } pslow.next = slow.next; return newhead.next; }}
Update 02/03/2014:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null || n==0) return null; ListNode newhead = new ListNode(-1); newhead.next = head; ListNode fast = head; ListNode slow = newhead; // slow points to one element before the one which should be deleted!!! for(int i=1; i<=n; i++) { if(fast!=null) fast=fast.next; else return null; } while(fast != null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return newhead.next; }}
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- 遍历json获得数据的几种方法
- sql之left join、right join、inner join的区别
- Remove Element
- 李振杰:网络安宁人人有责
- MySQL将某个数据库下的所有表的存储引擎修改为InnoDB类型语句
- Remove Nth Node From End of List
- 健康助手v2.0震撼上线 新功能模式开启
- XCode5添加新建类模板(Cocos2dx Template Class for Scene or Layer)
- 基于ASP.NET MVC+Linq等技术下的企业级通用OA系统全程开发
- Virtual Machine Optimization
- Meterpreter 脚本列表
- 【LoadRunner】手写HTTP请求,关于multipart/form-data类型
- 从excel 中导入数据到oracle
- C语言判断文件是否存在