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.
代码如下:
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         if(head==null)
12         return null;
13         
14         ListNode p=head;
15         int count=0;
16         while(p!=null)
17         {
18             count++;
19             p=p.next;
20         }
21         
22         if(n>count)
23         return head;
24         if(n==count)
25         return head.next;
26         
27         count=count-n;
28         p=head;
29         while(count!=1)
30         {
31             p=p.next;
32             count--;
33         }
34         
35         p.next=p.next.next;
36         return head;
37     }
38 }