题目: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.

就是让你删除单链表倒数第n个节点,同时希望能只遍历一次。

解法一: 如果不遍历完所有节点,怎么知道倒数第n个在哪里呢?但是遍历完成以后,删除不是又需要遍历么?不过删除一个node实际上只需要一个pre node就行了。于是,考虑使用一个HashMap保存遍历过的节点,实现删除。

 public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null) return null;
HashMap<Integer, ListNode> map = new HashMap<Integer, ListNode>();
int i = 0;
ListNode p = head;
while(p != null){
map.put(++i, p);
p = p.next;
}
ListNode pre = map.get(i - n);//i - n is the node that right BEFORE the to-be-deleted node.
if(pre != null){
ListNode deleted = pre.next;
if(deleted != null)
pre.next = deleted.next;
}else {//if pre is null, means we are deleting head
head = head.next;
}
return head;
}

HashSet deletion

感觉每次做题,如果用到了额外的数据结构或者空间,都有一种开挂的感觉。能不能不显式使用额外的空间或者数据结构呢?想到最近看了Algorithm 4th edtion关于递归删除BST的方法,有一些启发。

解法二: 我们尝试使用递归来解。

 public ListNode removeNthFromEnd2(ListNode head, int n) {
if(head == null) return null;
int[] counter = new int[]{0};
return removeNthFromEnd2(head,n,counter);
} private static ListNode removeNthFromEnd2(ListNode head, int n, int[] counter){
if(head.next == null){// we reached tail
counter[0] = 1;
}else {
head.next = removeNthFromEnd2(head.next, n, counter);
counter[0]++;//we increment this counter to record when we back from the recursive, namely back from the last node
}
if(counter[0] == n){//oh, this is nth node backward, we just RETURN THE NEXT NODE.
return head.next;
}else return head;//otherwise return whatever we received
}

recursive deletion

是不是看上去很简洁?同样的,我们还是需要遍历完所有节点。但是递归的好处是每次返回的都是“backward",通过这个特点,我们使用一个counter变量,在递归返回的时候,记录返回经过的节点(Java不如C#,没有ref参数,所以只能用一个数组记录这个counter变量以达到引用的效果)。这样当counter到打n的时候,我们知道,哦,好啦这个当前节点就是我们要删除的节点咯。所以,instead of直接返回head节点,我们返回删除节点的next,这样,在递归调用再次返回的时候,pre的next就指向了删除节点的next咯。

好吧,承认实际上这也是遍历了两次链表。。。:<

解法三: 为了减少遍历,我们还可以用两个指针slow和fast,fast先走n步。then,slow和fast共同进步直到fast走到尾巴。Code在这里

LeetCode 笔记系列四 Remove Nth Node From End of List的更多相关文章

  1. LeetCode解题报告—— 4Sum & Remove Nth Node From End of List & Generate Parentheses

    1. 4Sum Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + ...

  2. leetcode第19题--Remove Nth Node From End of List

    Problem: Given a linked list, remove the nth node from the end of list and return its head. For exam ...

  3. LeetCode之“链表”: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 ex ...

  4. LeetCode题解:(19) 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, ...

  5. LeetCode(19) 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, G ...

  6. 【leetcode❤python】 19. Remove Nth Node From End of List

    #-*- coding: UTF-8 -*-#双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针的后继就是要删除的节点# Definition for sin ...

  7. leetcode个人题解——#19 Remove Nth Node From End of List

    思路:设置两个指针,其中第二个指针比第一个延迟n个元素,这样,当第二个指针遍历到指针尾部时,对第一个指针进行删除操作. 当然,这题要注意一些边界值,比如输入[1,2] n=2时如果按照思路走会指向未分 ...

  8. LeetCode: Remove Nth Node From End of List 解题报告

    Remove Nth Node From End of List Total Accepted: 46720 Total Submissions: 168596My Submissions Quest ...

  9. 《LeetBook》leetcode题解(19):Remove Nth Node From End of List[E]——双指针解决链表倒数问题

    我现在在做一个叫<leetbook>的开源书项目,把解题思路都同步更新到github上了,需要的同学可以去看看 这个是书的地址: https://hk029.gitbooks.io/lee ...

随机推荐

  1. 批量修改图像的大小 Python PIL

    #-*-coding:utf-8-*- import os import os.path from PIL import Image import time def ResizeImage(filei ...

  2. 从JavaScript 数组去重看兼容性有关问题,及性能优化(摘自玉伯博客)

    JavaScript 数组去重经常出现在前端招聘的笔试题里,比如: 有数组 var arr = ['a', 'b', 'c', '1', 0, 'c', 1, '', 1, 0],请用 JavaScr ...

  3. IIS6 伪静态 IIS文件类型映射配置方法 【图解】

    1.右键点击 要设置网站的网站 2.属性 -->主目录 -->配置--> 3.如右侧窗口,找到 .aspx 扩展名-->编辑-->复制 可执行文件的路径-->关闭 ...

  4. 【Android】13.3 使用SQLite.NET-PCL访问SQLite数据库

    分类:C#.Android.VS2015: 创建日期:2016-02-26 一.简介 本章开头已经说过了,SQLite.NET-PCL用起来很爽,这一节咱们看看怎样使用吧. 二.示例3运行截图 下面左 ...

  5. struts2异常处理机制

    一.处理一般异常(javaBean异常) struts2进行异常处理首先需要添加exception拦截器,而默认拦截器栈已经加入了这个拦截器,所以不用特意的声明.在Struts 2框架中,采用声明式异 ...

  6. Git出现error: Your local changes to the following files would be overwritten by merge: ... Please, commit your changes or stash them before you can merge.的问题解决(Git代码冲突)

    在使用git pull拉取服务器最新版本时,如果出现error: Your local changes to the following files would be overwritten by m ...

  7. js 去html 标签

    var stylereg = /style\=".+?"/g //去style样式 var alltagreg = /<[^>]*>/g //去除全部标签 var ...

  8. vue 单元测试

    单元测试 配置和工具 任何兼容基于模块的构建系统都可以正常使用,但如果你需要一个具体的建议,可以使用Karma进行自动化测试.它有很多社区版的插件,包括对webpack和browserify的支持. ...

  9. JSON 文件格式解析

    JSON 文件大致说明 JSON 文件你可以理解为就是一个字典文件. 格式为 { 索引:数据, 索引:{ 索引:数据, 索引:{ 索引:数据, 索引:数据 } } } 自己写一个 my.json { ...

  10. EF常用查询语句

    //方法一 Linq to Entities            var info = from p in entity.Users where p.ID >= 10 orderby p.ID ...