import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
if(head==null||head.next==null){
return null;
}
ListNode cur=head;
int count=0;
while(cur!=null){//计算结点个数
count++;
cur=cur.next;
}
//找到要删除结点的位置
ListNode newHead=new ListNode(-1);//定义一个头结点
newHead.next=head;//将头结点加入链表
ListNode pre=newHead;//定义辅助结点,pre,post
ListNode post=newHead.next;
for(int i=0;i<count-n;i++){
post=post.next;
pre=pre.next;
}
//此时post指向删除的结点,pre指向前一节点
pre.next=post.next;
return newHead.next;
}
}