邻接表-单链表中的操作(插入头节点)讲解

代码讲解:

#include <iostream>
using namespace std;

const int N = 100000 + 10;
int e[N], ne[N], head, idx;

//初始化:
void init()
{
    head = -1;
    idx = 0;
}

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

//将x插入到下标为k的节点后面
void insert(int k, int x)
{
    e[idx] = x;
    //插入到k后面,那就将节点指向k节点的下一个节点
    ne[idx] = ne[k];    
    //再将原来指向下一节点的指向当前要插入的节点
    ne[k] = idx++;
}

//删除操作:删除下标为k的节点的下一个节点
void remove(int k)
{
    ne[k] = ne[ne[k]];
}


int main()
{
    int m;
    scanf("%d\n", &m);;

    init();

    while (m--)
    {
        int k = 0, x; char op;
        scanf("%c", &op);
        
        if (op == 'H')
        {
            scanf("%d\n", &x);
            add_to_head(x);
        }
        else if (op == 'D')
        {
            scanf("%d\n", &k);
            if (k == 0) head = ne[head];
            else remove(k - 1);
        }
        else
        {
            scanf("%d%d\n", &k, &x);
            insert(k - 1, x);
        }
    }

    for (int i = head; i != -1; i = ne[i]) printf("%d ", e[i]);
    printf("\n");

    return 0;
}

 关于上面的插入头节点操作:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值