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

2.删除链表倒数第N个节点

普通方法

ListNode *removeNthFromEnd(ListNode *head, int n) {
    if(head->next==nullptr)
        return nullptr;
        ListNode *first = head, *second = head;
        for (; n > 0; --n)
            if (first->next == nullptr)
                return head->next;
            else
                first = first->next;
        for (; first->next != nullptr; first = first->next, second = second->next);
        second->next = second->next->next;
        return head;
    }

空间换时间(似乎没什么卵用)

    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if (head->next == nullptr)
            return nullptr;
        vector<ListNode *> vec;
        ListNode *it = head;
        while (it != nullptr) {
            vec.push_back(it);
            it = it->next;
        }
        if (n == vec.size())
            return head->next;
        auto pos = vec.size() - n - 1;
        vec[pos]->next = (n == 1 ? nullptr : vec[pos+2]);
        return head;
    }

猜你喜欢

转载自www.cnblogs.com/INnoVationv2/p/10171894.html