双向链表

AcWing 827. 双链表

k处元素对应下标为k + 2

#include 
#include 
#include 
using namespace std;

const int N = 100005;

int e[N], l[N], r[N];
int head, tail, idx;

void init()
{
    idx = 2;
    head = 1, tail = 2;
    r[head] = tail, l[tail] = head;
}

void insert(int k, int x)//在k处元素后插入x
{
    e[++idx] = x;
    l[idx] = k;
    r[idx] = r[k];
    l[r[k]] = idx;
    r[k] = idx;
}

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

int main()
{
    int m, k, x;
    string s;
    cin >> m;
    
    init();
    while (m--)
    {
        cin >> s;
        if (s == "L") cin >> x, insert(head, x);
        else if (s == "R") cin >> x, insert(l[tail], x);
        else if (s == "D") cin >> k, remove(k + 2);
        else if (s == "IL") cin >> k >> x, insert(l[k + 2], x);
        else cin >> k >> x, insert(k + 2, x);
    }
    for (int i = r[head]; i != tail; i = r[i])
        cout << e[i] << ' ';
    
    return 0;
}

你可能感兴趣的:(双向链表)