普通方法

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;
    }

相关文章:

  • 2021-06-20
  • 2021-10-31
  • 2021-10-21
  • 2021-08-02
  • 2022-12-23
  • 2022-12-23
  • 2021-06-04
猜你喜欢
  • 2020-10-18
  • 2021-11-05
  • 2018-07-07
  • 2021-11-27
  • 2019-11-24
  • 2021-10-24
  • 2021-06-03
相关资源
相似解决方案