Remove Nth Node From End of List

Remove Nth Node From End of List

问题:

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

我的思路:

  使用HashMap<Object,Object>存储好位置

我的代码:

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || n <= 0)    return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        int count = 0;
        HashMap<Integer,ListNode> hm = new HashMap<Integer,ListNode>();
        hm.put(count++,dummy);
        while(head != null)
        {
            hm.put(count++,head);
            head = head.next;
        }
        int last = count - 1 - n;
        hm.get(last).next = hm.get(last).next.next;
        return dummy.next;
    }
}
View Code

他人代码:

   public ListNode removeNthFromEnd(ListNode head, int n) {

    ListNode start = new ListNode(0);
    ListNode slow = start, fast = start;
    slow.next = head;

    //Move fast in front so that the gap between slow and fast becomes n
    for(int i=1; i<=n+1; i++)   {
        fast = fast.next;
    }
    //Move fast to the end, maintaining the gap
    while(fast != null) {
        slow = slow.next;
        fast = fast.next;
    }
    //Skip the desired node
    slow.next = slow.next.next;
    return start.next;
}
View Code

学习之处:

  • 一般来说 降低时间的方法就是增加空间
  • 对于链表问题来讲,有各种技巧哇,一个快指针,一个慢指针,快慢可以是一个先走(先走多少也可以进行计算的),一个后走,也可以是同时出发一个步长是1,一个步长是2,都可以完成在一次遍历中做好多事情
  • 还可以通过一个步长为2快指针和一个步长为1慢指针在一个链表里面访问的话,快指针达到Null的时候,慢指针恰好在mid处。

posted on 2015-03-11 15:37  zhouzhou0615  阅读(181)  评论(0编辑  收藏  举报

导航