算法学习笔记(10)——单链表

单链表

题目链接:AcWing 826. 单链表

#include <iostream>

using namespace std;

const int N = 100010;

int n;
int e[N], ne[N], head, idx;

void init()
{
    idx = 0;
    head = -1;
}

void add_to_head(int x)
{
    e[idx] = x;
    ne[idx] = head;
    head = idx;
    idx ++;
}

void add(int k, int x)
{
    e[idx] = x;
    ne[idx] = ne[k];
    ne[k] = idx;
    idx ++;
}

void remove(int k)
{
    ne[k] = ne[ne[k]];
}

int main()
{
    cin >> n;
    
    init();
    while (n -- ) {
        char op;
        int k, x;
        cin >> op;
        if (op == 'H') {
            cin >> x;
            add_to_head(x);
        }
        else if (op == 'D') {
            cin >> k;
            if (!k) head = ne[head];
            else remove(k - 1);
        }
        else {
            cin >> k >> x;
            add(k - 1, x);
        }
    }
    
    for (int i = head; i != -1; i = ne[i]) cout << e[i] << ' ';
    
    return 0;
}
posted @ 2022-12-09 22:05  S!no  阅读(12)  评论(0编辑  收藏  举报