Acwing---826.单链表

1.题目

实现一个单链表,链表初始为空,支持三种操作:

向链表头插入一个数;删除第 k k k 个插入的数后面的数;在第 k k k 个插入的数后插入一个数。现在要对该链表进行 M M M 次操作,进行完所有操作后,从头到尾输出整个链表。

注意:题目中第 k k k 个插入的数并不是指当前链表的第 k k k 个数。例如操作过程中一共插入了 n n n 个数,则按照插入的时间顺序,这 n n n 个数依次为:第 1 1 1个插入的数,第 2 2 2 个插入的数,…第 n n n 个插入的数。

输入格式
第一行包含整数 M M M,表示操作次数。

接下来 M M M 行,每行包含一个操作命令,操作命令可能为以下几种:

  1. H x,表示向链表头插入一个数 x x x
  2. D k,表示删除第 k k k 个插入的数后面的数(当 k k k 0 0 0 时,表示删除头结点)。
  3. I k x,表示在第 k k k 个插入的数后面插入一个数 x x x(此操作中 k k k 均大于 0 0 0)。

输出格式
共一行,将整个链表从头到尾输出。

数据范围
1 ≤ M ≤ 100000 1≤M≤100000 1M100000
所有操作保证合法。 所有操作保证合法。 所有操作保证合法。

输入样例:

10
H 9
I 1 1
D 1
D 0
H 6
I 3 6
I 4 5
I 4 5
I 3 4
D 6

输出样例:

6 4 6 5

2.基本思想

在这里插入图片描述
最终结果如下:
在这里插入图片描述

3.代码实现

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class _826单链表 {
    static int N = 100010;
    private static int head, idx;
    private static int[] e = new int[N], ne = new int[N];

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

    private static void addToHead(int val) {
        e[idx] = val;
        ne[idx] = head;
        head = idx++;
    }

    private static void Delete(int k) {
        ne[k] = ne[ne[k ]];//此处需要 k-1 第几个对应到坐标要-1
    }

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

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int m = Integer.parseInt(br.readLine());
        init();
        while (m-- > 0) {
            String[] s = br.readLine().split(" ");
            String opt = s[0];
            if (opt.equals("H")) {
                int val = Integer.parseInt(s[1]);
                addToHead(val);
            } else if (opt.equals("D")) {
                int k = Integer.parseInt(s[1]);
                if (k == 0) head = ne[head];
                else Delete(k-1);
            } else {
                int k = Integer.parseInt(s[1]);
                int val = Integer.parseInt(s[2]);
                add(k-1, val);
            }
        }
        for (int i = head; i != -1; i = ne[i]) System.out.print(e[i] + " ");
    }
}
  • 19
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

amant 柒少

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值