AcWing 826. 单链表 Java
原题链接
简单
作者:
leo_0
,
2020-06-22 14:40:41
,
所有人可见
,
阅读 473
题目描述
算法1
Java 代码
import java.io.*;
import java.util.Scanner;
public class Main {
private static int N = 100010;
private static int[] e = new int[N];
private static int[] ne = new int[N];
private static int head;
private static int idx;
private static void init() {
head = -1;
idx = 0;
}
private static void addToHead(int val){
e[idx] = val;
ne[idx] = head;
head = idx;
idx++;
}
private static void remove(int k){
ne[k] = ne[ne[k]];
}
private static void insert(int k, int val){
e[idx] = val;
ne[idx] = ne[k];
ne[k] = idx;
idx++;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(reader.readLine());
init();
while (m-- > 0) {
String[] s = reader.readLine().split(" ");
if (s[0].equals("H")) {
int val = Integer.parseInt(s[1]);
addToHead(val);
} else if (s[0].equals("I")) {
int k = Integer.parseInt(s[1]);
int val = Integer.parseInt(s[2]);
insert(k-1, val);
} else {
int k = Integer.valueOf(s[1]);
if(k==0) head = ne[head];
else remove(k-1);
}
}
for (int i = head; i != -1; i = ne[i]) {
System.out.print(e[i] + " ");
}
}
}