classSolution{publicListNoderemoveNthFromEnd(ListNode head,int n){//设置哑节点,方便只有一个元素时删除节点。ListNode dummy =newListNode(0, head);int len =0;ListNode cur = head;//统计链表长度while(cur !=null){
len++;
cur = cur.next;}int i =1;
cur = dummy;//cur从哑节点开始//从哑节点开始遍历,链表长度为n+1。最后cur指向倒数n+1个位置while(cur !=null&& i < len +1- n){
i++;
cur = cur.next;}//删除第n个节点
cur.next = cur.next.next;return dummy.next;}}