Leetcode 19. Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

/**
 * 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) {
        using namespace std;
        /*
        边界:要删的可能是第一个,也可能是最后一个;
        */
        ListNode *p=head,*pre=head;
        while(n--) p=p->next;
        if(p==NULL){
            head=head->next;
            delete pre;
            return head;
        }
        p=p->next;
        while(p){
            p=p->next;
            pre=pre->next;
        }
        p=pre->next;
        pre->next=p->next;
        delete p;
        return head;
    }
};
posted @ 2019-05-04 09:40  benda  阅读(78)  评论(0编辑  收藏  举报