删除链表的倒数第N个节点

题目链接:删除链表的倒数第N个节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* p,*q,*s;
        int cnt = 0;
        p = head;
        q = p;
        s = p;
        //q先向前走n-1步
        while(cnt<n-1){
            q = q->next;
            cnt++;
        }
        //p和q一起向前走,
        while(q->next){
            s = p;
            p = p->next;
            q = q->next;
        }
        s->next = p->next;
        if(p == head){
            //head = NULL;
            head = head->next;
        }
        delete p;   //释放内存
        p = NULL;   //这个比较重要,提示head use after free的bug
        return head;
    }
};
posted @ 2020-09-24 14:38  focusDing  阅读(94)  评论(0)    收藏  举报