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;
        }
    
  • 相关阅读:
    swoole 查看tcp开启进程数
    详解LRU缓存算法
    glib 双向链表
    清华计算机本科 课表
    glib 单向链表
    通信课程
    基数排序
    glib 数组
    glib 散列表
    清华计算机博士 课表
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10171894.html
Copyright © 2011-2022 走看看