模板 - 双向链表

一种头节点和尾节点都是虚拟节点的双向链表。

const int MAXN=500000;

struct ListNode {
    ListNode *prev, *next;
    int val;
};

struct List {
    ListNode ln[MAXN+5];
    ListNode *head, *tail;

    int top, size;

    void Init() {
        //head,tail都是虚拟节点
        top = 0, size = 0;
        head = NewNode(-1, nullptr, &ln[1]);
        tail = NewNode(-1, &ln[0], nullptr);
    }

    ListNode *NewNode(int val, ListNode *prev, ListNode *next) {
        ln[top].val = val;
        ln[top].prev = prev;
        ln[top].next = next;
        return &ln[top++];
    }

    void InsertHead(int val) {
        Insert(val, head);
    }

    void InsertTail(int val) {
        Insert(val, tail->prev);
    }

    void Insert(int val, ListNode *pn) {
        //在pn后面插入
        ListNode *newNode = NewNode(val, pn, pn->next);
        pn->next->prev = newNode;
        pn->next = newNode;
        ++size;
    }

    void Delete(ListNode *pn) {
        //删除pn
        pn->prev->next = pn->next;
        pn->next->prev = pn->prev;
        --size;
    }
} L;
posted @ 2019-07-26 14:57  韵意  阅读(186)  评论(0编辑  收藏  举报