AcWing 826. 单链表
原题链接
简单
作者:
haah
,
2020-12-11 19:42:18
,
所有人可见
,
阅读 375
JAVA代码
package acwing_projects;
import java.io.*;
import java.util.Scanner;
/**
* @Author: ChangAo
* @Date: 2020/12/11 19:06
*/
public class SingleLink_826 {
public static int N = 10000;
public static int head; // 头指针
public static int idx; // 节点位置
public static int[] e = new int[N]; // 存储节点的值
public static int[] nex = new int[N]; // 存储下一节点的地址
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
init();
int M = Integer.parseInt(br.readLine());
for (int i = 0; i < M; i++) {
String[] res = br.readLine().split(" ");
switch (res[0]) {
case "H": add(Integer.parseInt(res[1]));break;
case "D": {
if (Integer.parseInt(res[1]) == 0)
head = nex[head];
else delete(Integer.parseInt(res[1]) - 1); }break;
case "I": insert(Integer.parseInt(res[1]) - 1, Integer.parseInt(res[2]));break;
}
}
for (int i = head; i != -1; i = nex[i])
System.out.print(e[i] + " ");
}
// 初始化头指针和节点位置
public static void init(){
head = -1;
idx = 0;
}
public static void add(int x){
e[idx] = x; // 将值赋给第一个节点的值
nex[idx] = head; // 将头指针指向的地址赋给nex
head = idx;
idx++;
}
public static void delete(int k){
nex[k] = nex[nex[k]];// 直接让k节点指向下下个节点
}
public static void insert(int k, int x){
e[idx] = x;
nex[idx] = nex[k];
nex[k] = idx;
idx++;
}
}