019Remove Nth Node From End of List

来源:互联网 发布:网络p2p靠谱吗 编辑:程序博客网 时间:2024/06/07 00:35
删除倒数第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;    }}