【leetcode】Remove Nth Node From End of List(easy)

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

For 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.

思路:

最基本的思路肯定是用两个指针,一个先走n+1步,然后再两个同时走,这样后走的指针一定是在要删除指针的前一格。

问题主要是如果要删除的是头结点,走到n步的时候肯定就NULL了,所以要加个判断,如果在没有走完n+1步时遇到了 先走指针指向NULL,则返回head->next

唉,就这一点一点逻辑关系晕了好久。要先分析清楚再做题,不要每次都只是靠感觉...感觉在这种边界条件时特别的不靠谱...

ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode * p1 = head, * p2 = head;
        n++;
        while(n--) //p1先走n+1步
        {
            p1 = p1->next;
            if(p1 == NULL && n != 0) //遇到删除头指针情况
                return head->next;
        }
        while(p1 != NULL) //p1走到头时, p2正好在要删除的指针前面
        {
            p1 = p1->next;
            p2 = p2->next;
        }
        p2->next = p2->next->next; //删除指定指针
        return head;
    }
原文地址:https://www.cnblogs.com/dplearning/p/4231100.html