数组模拟单链表

题目链接 Acwing 826单链表

在这里插入图片描述
在这里插入图片描述

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5+10;
//head表示头结点的下标,e[i]表示节点i的值,ne[i]表示节点i的下一个的位置,index表示正在用哪个点
int e[N] , ne[N] , head , idx; 

//初始化
void init()
{
    head = -1;      //head指向空节点
    idx = 0;     //从第一个点开始用
}

//将x插入头结点
void add_to_head(int x)
{
    e[idx] = x;
    ne[idx] = head;
    head = idx ; 
    idx++;
}

//将x插到下标是k的点的后面
void add(int k,int x)
{
    e[idx] = x;
    ne[idx] = ne[k];
    ne[k] = idx;
    idx++;
}

//删除下标为k后面的节点
void remove(int k)
{
    ne[k] = ne[ne[k]];
}

int main ()
{
    init();
    int m;
    cin>>m;
    while (m--)
    {
        int k,x;
        char op;
        cin>>op;
        if (op=='H') 
        {
            cin>>x;
            add_to_head(x);
        }
        else if (op=='D')
        {
            cin>>k;
            if (!k) head = ne[head];
            remove(k-1);
        }
        else
        {
            cin>>k>>x;
            add(k-1,x);
        }
    }
    
    for (int i = head ; i != -1 ; i = ne[i]) cout<<e[i]<<' ';  //-1表示尾节点
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值