数组模拟单链表

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

向链表头插入一个数;
删除第 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();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值