Remove Nth Node From End of List
来源:互联网 发布:经济和信息化数据平台 编辑:程序博客网 时间:2024/05/21 09:04
Question: Given a linked list, remove the nth node from the end of list and return its head. 给定一个数值n, 从序列的末尾算起, 删除序列中的第n个节点.
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: 1. Given n will always be valid. 2. Try to do this in one pass. 1. 假设n总是有效的 2. 解决此问题只便利序列一次
Solution: Take advantage of fast pointer and slow pointer to traverse the list. Fast pointer is n ahead of slow pointer, when fast pointer gets to the end of list, the node that slow points is the one should be removed.
public class RemoveNodeFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || head.next == null){
return null;
} else {
ListNode temp = new ListNode(0);
temp.next = head;
ListNode cur = temp;
ListNode slow = temp;
for(int i = 0; i < n; i++){
temp = temp.next;
}
ListNode fast = temp;
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
if(slow.next == null){
return null;
} else {
slow.next = slow.next.next;
}
return cur.next;
}
}
}
- 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
- 123
- Merge Two Sorted Lists
- 一年小结
- 笔试题:动态规划之求数组中的最长路径
- NSThread 和锁机制
- Remove Nth Node From End of List
- 黑马程序员—JAVA基础学习日志——由synchronized线程锁引发
- 关于java的动态代理
- 做让自己快乐的事,有利的事——我被骗了
- 国内Java学习网站汇总
- 适配器模式
- 比较好的winform-dataGridView例程网站
- 定义一个TreeMap,键存储的是书对象,值存储的是字符串。 根据书的出版出版日期排序。
- 设计模式-中介者模式