这个题目楼主用了比较骚气的做法,通过递归的方法去做:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//设定计数常量
int count=0;
//获取目标节点的前一个节点
ListNode tempNode=new ListNode(0);
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode tmpHead=head;
//当只有一个元素的时候,直接返回null。
if(n==1&&head.next==null)return null;
try{
run(head,n);
}catch(Exception e){
//删除获取节点的下一个节点
tempNode.next=tempNode.next.next;
return tmpHead;
}
return tmpHead.next;
}
//使用递归遍历
public void run(ListNode head, int n)throws Exception{
ListNode tmp=head;
if(head.next==null){
count+=1;
return;
}
//递归调用
run(head.next,n);
//当返回的计数为n时,强行中断递归抛出异常,将删除目标节点的上一个节点返回
if(count==n){
//将当前的节点赋值给全局的临时节点
tempNode=tmp;
throw new Exception();
}else{
//倒过来计数
count+=1;
return;
}
}
}