删除倒数第N个链表节点,快慢指针,快的先走几步,然后慢点再走,如果是第一个需要特殊处理一下,其他情况直接返回即可,还需要提高解题速度啊....
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pAhead = head;
ListNode pBehind = head;
//快指针先走n步 ,题目说了n为有效值,所以不用判断n的有效性
for (int i = 0; i < n; i++) {
pAhead = pAhead.next;
}
//如果是倒数第N个,即第一个head需要处理一下
if (pAhead == null) {
return head.next;
}
while (pAhead != null && pAhead.next != null) {
pAhead = pAhead.next;
pBehind = pBehind.next;
}
pBehind.next = pBehind.next.next;
return head;
}
}