zoukankan      html  css  js  c++  java
  • 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;
        }
    
  • 相关阅读:
    无缝轮播图
    瀑布流之ajax
    进阶版轮播图
    桌面特效
    3D模型文字动画
    Razor 常用方法
    easyui常用
    C#
    Redis设置记录
    日志三剑客ELK
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10171894.html
Copyright © 2011-2022 走看看