Remove Nth Node from End of List
Given A linked list, remove the nth node from the end of the list and return its head.
Example
Given linked List:1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.
Note
The minimum number of nodes in list is n.
Challenge
O (N) time
Solution:
Stupid method is to walk again, determine the length of the list, and then go through the length of the len-n, but asked O (n) to use two pointers, the first pointer to walk N, the second to go, when the first pointer has reached the end, the second pointer with a natural difference N, However, when you delete the list node, you need to record the point in front of node before deleting it.
Code:
/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; * } * } */ Public classSolution {/** * @paramhead:the first node of linked list. * @paramN:an Integer. * @return: The head of linked list. */ListNode Removenthfromend (ListNode head,intN) {if(Head = =NULL|| N < 1){ returnHead; } ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode Predel=dummy; for(inti = 0; I < n; i++){ if(Head! =NULL) {Head=Head.next; } } while(Head! =NULL) {Head=Head.next; Predel=Predel.next; } Predel.next=PreDel.next.next; returnDummy.next; }}View Code
[Lintcode] Remove Nth Node from End of List