删除链表的倒数第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 *dummy=new ListNode(-1);
        dummy->next=head;
        ListNode *slow=head, *fast=head,*pre=dummy;
        for(int i=0;i<n;i++){
            fast=fast->next;
        }

        while(fast){
            pre=slow;
            slow=slow->next;
            fast=fast->next;
        }
        pre->next=slow->next;
        return dummy->next;
    }
};

 

posted @ 2020-03-07 17:09  7aughing  阅读(82)  评论(0编辑  收藏  举报