Que21|826. 单链表

44 阅读1分钟
题目:826. 单链表 - AcWing题库
思路/想法:

image.png

image.png

代码实现:
import java.util.*;
public class Main{
    static int[] e = new int[100010]; // 封装值
    static int[] ne = new int[100010]; // 封装下标
    static int idx, head; // 下标,头节点
    public static void init() { // 初始化
        idx = 0;
        head = -1;
    }
    // 向链表头插入一个数x
    public static void addHead(int x) {
        e[idx] = x;
        ne[idx] = head;
        head = idx++;
    }
    // 在第k个位置上插入x
    public static void add(int k, int x) {
        e[idx] = x;
        ne[idx] = ne[k];
        ne[k] = idx++;
    }
    // 删除第k个位置上的节点
    public static void remove(int k) {
        ne[k] = ne[ne[k]];
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        
        init();
        while (m-- > 0) {
            char op = sc.next().charAt(0);
            if (op == 'H') {
                int x = sc.nextInt();
                addHead(x);
            } else if (op == 'D') {
                int k = sc.nextInt();
                if (k == 0) {
                    head = ne[head];
                } else {
                    remove(k - 1);
                }
            } else {
                int k = sc.nextInt();
                int x = sc.nextInt();
                add(k - 1, x);
            }
        }
        for (int i = head; i != -1; i = ne[i]) {
            System.out.print(e[i] + " ");
        }
    }
}