Problem description
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Algorithm
Code One
1 PublicListNode Removenthfromend (ListNode head,intN) {2Hashmap<integer, integer> map =NewHashmap<integer, integer>();3ListNode p =Head, q;4 intindex = 1;5 while(P.next! =NULL) {6 map.put (index, p.val);7index++;8p =P.next;9 }Ten map.put (index, p.val); One intKey = index + 1-N; A intval = map.get (index + 1-n); -p = q =head; - for(inti = 1; I < key; i++) { theQ =p; -p =P.next; - } - if(p = =q) +Head =P.next; - Else { +Q.next =P.next; A } at returnhead; -}
Code two
1 /**2 * 3 * @authoraudr004 * A One pass solution can is done using pointers. Move one pointer fast-to n+1 places forward,5 * To maintain a gap of n between the both pointers and then move both at the same speed. Finally,6 * When the fast pointer reaches the end, the slow pointer 'll be n+1 places behind-just the right7 * spot for it is able to skip the next node.8 * Since The question gives that n was valid, not too many checks has to being put in place. Otherwise,9 * This would is necessary.Ten * One */ A PublicListNode Removenthfromend (ListNode head,intN) { - -ListNode start =NewListNode (0); theListNode slow = start, fast =start; -Slow.next =head; - - //Move fast in front so, the gap between slow and fast becomes n + for(intI=1; i<=n+1; i++) { -Fast =Fast.next; + } A //Move Fast to the end, maintaining the gap at while(Fast! =NULL) { -slow =Slow.next; -Fast =Fast.next; - } - //Skip the desired node -Slow.next =Slow.next.next; in returnStart.next; - } to Public Static voidMain (String[]args) { + //new RemoveNthFromEnd1 (). Removenthfromend (head, N) -}
Remove Nth Node from End of List