网站建设教学课件友情链接可以随便找链接加吗
实现一个单链表,链表初始为空,支持三种操作:
向链表头插入一个数;
删除第 k个插入的数后面的数;
在第 k个插入的数后插入一个数。
现在要对该链表进行 M次操作,进行完所有操作后,从头到尾输出整个链表。
注意:题目中第 k个插入的数并不是指当前链表的第 k个数。例如操作过程中一共插入了 n个数,则按照插入的时间顺序,这 n个数依次为:第 1
个插入的数,第 2个插入的数,…第 n个插入的数。
输入格式
第一行包含整数 M,表示操作次数。接下来 M 行,每行包含一个操作命令,操作命令可能为以下几种:
H x,表示向链表头插入一个数 x。
D k,表示删除第 k个插入的数后面的数(当 k为 0时,表示删除头结点)。
I k x,表示在第 k
个插入的数后面插入一个数 x(此操作中 k 均大于 0)。
输出格式
共一行,将整个链表从头到尾输出。
import java.util.*;
import java.io.*;public class Main {static int INF = 0x3f3f3f3f;static int MOD = 998244353;static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));static int n;static int N = 100010;static int head = -1;static int e[] = new int [N];static int ne[] = new int [N];static int idx = 1;static void add_to_head(int x) {e[idx] = x; ne[idx] = head; head = idx ++;}static void add_to_k(int k ,int x) {e[idx] = x; ne[idx] = ne[k]; ne[k] = idx; idx ++;}static void remove(int k) {ne[k] = ne[ne[k]];}public static void main(String[] args) throws IOException {Scanner sc = new Scanner(System.in);n = sc.nextInt();while(n --> 0) {char s = sc.next().charAt(0);if(s == 'H') {int x = sc.nextInt();add_to_head(x);}else if(s == 'D') {int k = sc.nextInt();if(k == 0) head = ne[head];else remove(k);}else {int k = sc.nextInt();int x = sc.nextInt();add_to_k(k, x);}}for(int i = head; i != -1; i = ne[i] ) {System.out.println(e[i]);}sc.close();pw.close();}
}