码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Nth Node From End of List

时间:2015-03-11 16:35:32      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

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,都可以完成在一次遍历中做好多事情

Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4330081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!