标签:
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; } }
他人代码:
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; }
学习之处:
Remove Nth Node From End of List
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4330081.html