19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // ListNode dummy = new ListNode(0);
        // dummy.next = head;
        // int l = 0;
        // ListNode curr = head;
        // while(curr!=null){
        //     l++;
        //     curr = curr.next;
        // }
        // curr = dummy;
        // l-=n;
        // while(l>0){
        //     l--;
        //     curr = curr.next;
        // }
        // curr.next = curr.next.next;
        // return dummy.next;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode p = dummy, q = dummy;

        for (int i = 0; i < n; i++)  // q先走n步
            q = q.next;

        while(q.next != null) { // 一起走
            p = p.next;
            q = q.next;
        }
        p.next = p.next.next;
        return dummy.next;
    }
}

典型的双指针题。设两个指针p,q,让q先走n步,然后pq一起走,直到q走到尾节点,删除p->next即可。

处理此类问题时能用dummy.next就用,否则直接用head容易出错。

啥意思?倒数n个就等于正数l - n个,那l - n怎么得到?我们知道n + l - n = l,那我们让快指针先走n步,剩下的就是l - n,这时候让快慢指针一起走即可。

posted @ 2019-08-21 04:06  Schwifty  阅读(136)  评论(0编辑  收藏  举报