Remove Nth Node From End of List 的
来源:互联网 发布:网络电影市场规模 编辑:程序博客网 时间:2024/05/22 09:48
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点
一.目标:如上
二.思路:使用两个节点,让一个节点领先n+2,当开头的节点走到null 时,后一个节点走到了要删除的节点的前节点,此时可进行删除。
三.易错点:分不清到底领先多少步和判断 n 与链表的长度的关系
代码如下:
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
if(n < 0){
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode preDelete = dummy;
for(int i = 0; i < n; i++){
if(head == null){
return null; //必须 因为也许给的数值不符合链表情况
}
head = head.next;
}
while(head != null){
head = head.next;
preDelete = preDelete.next;
}
preDelete.next = preDelete.next.next;
return dummy.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
- uva 11384 把n个数都变为0要多少次操作
- 深入理解openstack网络架构(三)
- 初识ViewPager
- activiti工作流引擎使用
- [BZOJ2521][Shoi2010]最小生成树(最小割)
- Remove Nth Node From End of List 的
- ASP.NET缓存之数据库缓存依赖(一)
- 深入理解openstack网络架构(四)
- vue学习之一基础学习
- JZOJ.4693【NOIP2016提高A组模拟8.14】疯狂的火神
- zend studio常用快捷键锦集
- Android中dip、dp、sp、pt和px的区别
- 关于编码
- 结构体指针