单链表模板

#include<iostream>

using namespace std;
const int N=100010;

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

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

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

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

//删除的是k后面的一个点
void remove(int k){
    ne[k]=ne[ne[k]];
}

int main(){
    int m;
    cin>>m;
    init();
    while(m--){
        int k,x;
        char c;
        cin>>c;
        if(c=='H'){
            cin>>x;
            add_to_head(x);
        }else if(c=='D'){
            cin>>k;
            if(!k) head=ne[head];//这里的k和形参k不同相差1.函数中k=0是值结点,题设是头结点
            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-01-02 13:43  秋月桐  阅读(41)  评论(0编辑  收藏  举报