Link: http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
1 //using two pointer, one pointer is n steps ahead of another 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 if (head == null||head.next==null) 4 return null; 5 ListNode p1 = head; 6 ListNode p2 = head; 7 ListNode result = head; 8 //n--; 9 while(n-->0){ 10 p1 = p1.next; 11 } 12 //special case: 13 //input: {1,2} 2 14 //in this case, we should delete the head; 15 if(p1==null){ 16 return head.next; 17 } 18 while (p1.next!=null){ 19 p1 = p1.next; 20 p2 = p2.next; 21 } 22 p2.next= p2.next.next; 23 return result; 24 }