826. 单链表

55 阅读2分钟

826. 单链表 - AcWing题库

Question

Content

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

  1. 向链表头插入一个数;
  2. 删除第 k 个插入的数后面的数;
  3. 在第 k 个插入的数后插入一个数。

现在要对该链表进行 M 次操作,进行完所有操作后,从头到尾输出整个链表。

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

输入格式

第一行包含整数 M ,表示操作次数。

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

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

输出格式

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

数据范围

1 ≤ M ≤ 100000

所有操作保证合法。

输入样例:

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

Solution

Java

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

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
        int m = Integer.parseInt(scanner.readLine());

        LinkedList linkedList = new LinkedList();

        while (m-- > 0) {
            String[] s = scanner.readLine().split(" ");

            if ("H".equals(s[0])) {
                int x = Integer.parseInt(s[1]);
                linkedList.insert(x);
            } else if ("D".equals(s[0])) {
                int k = Integer.parseInt(s[1]);
                if (k == 0) {
                    linkedList.remove();
                } else {
                    linkedList.remove(k - 1);
                }
            } else {
                int k = Integer.parseInt(s[1]);
                int x = Integer.parseInt(s[2]);
                linkedList.add(k - 1, x);
            }
        }

        for (int i = linkedList.head; i != -1; i = linkedList.ne[i]) {
            System.out.print(linkedList.e[i] + " ");
        }
    }

    public static class LinkedList {
        private static final int N = 100010;
        private int head, idx;
        private int[] e = new int[N];
        private int[] ne = new int[N];

        private LinkedList() {
            head = -1;
            idx = 0;
        }

        public void insert(int val) {
            e[idx] = val;
            ne[idx] = head;
            head = idx++;
        }

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

        public void remove() {
            head = ne[head];
        }

        public void remove(int k) {
            ne[k] = ne[ne[k]];
        }
    }

}