Posted on

Description

Submission 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        vector<ListNode*> list;
        for(ListNode* p = head; p != nullptr; p = p->next) {
            list.push_back(p);
        }
        int target = list.size() - n;
        if(target == 0) return head->next;
        list[target - 1]->next = list[target]->next;
        return head;
    }
};

Submission 2

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int count = 0;
        for(ListNode* p = head; p != nullptr; count++, p = p->next);
        int target = count - n;
        if(target == 0) return head->next;
        ListNode* t, *prev;
        for(t = head; target != 0; target--) {
            prev = t;
            t = t->next;
        }
        prev->next = t->next;
        return head;
    }
};

Submission 210730

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode(-1, head);
        ListNode *first = dummy, *second = dummy;

        for(int i = 0; i <= n; ++i, second = second->next);
        for(; second; first = first->next, second = second->next);
        first->next = first->next->next;
        
        return dummy->next;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *