经典的模拟链表
查看原帖
经典的模拟链表
638272
thehanged楼主2024/4/19 20:03

虽然是经典模拟(也就是静态链表),但哪有这样玩的,直接给定一个元素插入该元素后,还好数据范围小。。

代码如下,没啥好说的

#include <iostream>
#include <cstring>
using namespace std;

const int N = 1e6 + 10;
int head, e[N], ne[N], idx; // e[pos] = value ne[value] = pos

inline int read(){
	int x = 0;
	bool is_neg = false;
	char c = 0;
	while((c = getchar()) == ' ' || c == '\r' || c == '\n') break;
	if(c == '-')
		is_neg = true;
	else
		x = c - '0';
	while(isdigit(c = getchar())){
		x = (x << 3) + (x << 1) + c - '0';
	}
	return is_neg ? -1 * x : x;
}

void init(){
	head = 0;
	e[head] = 1;
	ne[e[head]] = -1;
	idx = 1;
}

// 将元素x插入到元素k后 
void add(int k, int x){
	e[idx] = x;
	ne[e[idx]] = ne[k];
	ne[k] = idx;
	idx ++;
}

// 删除元素k后面的元素 
void remove(int k){
	if(ne[k] == -1) return ;
	ne[k] = ne[e[ne[k]]];
}

int main(){
	int q = read();
	memset(ne, -1, sizeof ne);
	init();
	while(q --){
		int a, b, c;
		a = read();
		if(a == 1){
			b = read(), c = read();
			add(b, c);
		}
		else if(a == 2){
			b = read();
			cout << (ne[b] == -1 ? 0 : e[ne[b]]) << endl; 
		}else{
			b = read();
			remove(b);
		}
	}
	return 0;
}
2024/4/19 20:03
加载中...