AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

AcWing 826. 单链表-C++    原题链接    简单

作者: 作者的头像   Struggle ,  2020-05-20 23:32:28 ,  阅读 259


3


注释版

#include<iostream>
using namespace std;
const int N=100010;
int value[N],nex[N],index,head;
void initializer()
{
    head=-1;
    index=0;
}
void add_to_head(int x)
{
    //新节点保存值
    value[index]=x;
    //新节点与原来头节点连的节点相连
    nex[index]=head;
    //更新头结点
    head=index;
    //更新index;
    index++;
}
//删除第x个节点后一个的节点
void remove1(int k)
{
    nex[k]=nex[nex[k]];
}
//在k+1后一个节点上插入值为x的节点
void add(int k,int x)
{
    value[index]=x;
    nex[index]=nex[k];
    nex[k]=index;
    index++;
}
int main()
{
    initializer();
    int m;
    cin>>m;

    while(m--)
    {
        char op;
        int x;
        int k;
        cin>>op;
        switch(op)
        {
            case 'H':
            {
                cin>>x;
                add_to_head(x);
            }break;
            case 'D':
            {
                cin>>k;
                if(!k) head=nex[head];
                remove1(k-1);
            }break;
            default:
            {
                cin>>k>>x;
                add(k-1,x);
            }
        }
    }
    while(head!=-1)
    {
        cout<<value[head]<<" ";
        head=nex[head];
    }
    return 0;

}

无注释版

#include<iostream>
using namespace std;
const int N=1e5+10;
int head,idx=-1,e[N],ne[N];

void init()
{
    head=-1;
}
void insert_to_head(int x)
{
    e[++idx]=x;
    ne[idx]=head;
    head=idx;
}
void del(int x)
{
    ne[x]=ne[ne[x]];
}
void insert(int k,int x)
{
    e[++idx]=x;
    ne[idx]=ne[k];
    ne[k]=idx;
}
int main()
{
    int m;
    cin>>m;
    init();
    while(m--)
    {
        char op[2];
        cin>>op;
        if(op[0]=='H')
        {
            int x;
            cin>>x;
            insert_to_head(x);
        }
        else if(op[0]=='D')
        {
            int k;
            cin>>k;
            if(k)  del(k-1);
            else{//delete head node
                head=ne[head];
            }

        }
        else{
            int k,x;
            cin>>k>>x;
            insert(k-1,x);
        }
    }
    for(;head!=-1;head=ne[head]) cout<<e[head]<<' ';
    return 0;
}

0 评论

你确定删除吗?

© 2018-2021 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息