Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

 1 public class Solution {
 2     public ListNode removeNthFromEnd(ListNode head, int n) {
 3         ListNode safe = new ListNode(-1);
 4         safe.next = head;
 5         ListNode p1 = safe;
 6         for(int i=0;i<=n;i++){
 7             p1 = p1.next;
 8         }
 9         ListNode p2 = safe;
10         while(p1!=null){
11             p1 = p1.next;
12             p2 = p2.next;
13         }
14         p2.next=p2.next.next;
15         return safe.next;
16     }
17 }
View Code

 

posted @ 2014-02-06 05:33  krunning  阅读(94)  评论(0编辑  收藏  举报