给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
设置快慢指针,first指针比second指针先走n步,当first指针为null时,则删除second.next=second.next.next即可
返回结果即可
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre=new ListNode(0,head);
ListNode first=head;
ListNode second=pre;
while(n>0){
first=first.next;
n--;
}
if(first==null)return head.next;
while(first!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return pre.next;
}
来源于LeetCode.19
原文:https://www.cnblogs.com/zhimeng-yabiao/p/14675481.html