在部分算法题中可能会用到链表,如果创造一个传统的链表再进行操作
会浪费很多时间,于是使用数组来模拟链表,由于只是单纯的做题,一些
细节可以忽略。
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 const int N = 100010; 5 int idx, e[N], ne[N], head; 6 void init(){ //初始化 7 idx = 0; 8 head = -1; 9 } 10 void add_to_head(int x){ //往头节点添加节点 11 e[idx] = x; 12 ne[idx] = head; 13 head = idx; 14 idx ++; 15 } 16 void add(int k, int x){ 17 e[idx] = x; 18 ne[idx] = ne[k]; 19 ne[k] = idx; 20 idx ++; 21 } 22 void remove(int k){ 23 ne[k] = ne[ne[k]]; 24 } 25 int main(){ 26 init(); 27 int m; 28 cin >> m; 29 while(m --){ 30 int x; 31 char op; 32 cin >> op; 33 if(op == 'H'){ 34 cin >> x; 35 add_to_head(x); 36 }else if(op == 'I'){ 37 int k; 38 cin >> k >> x; 39 add(k - 1, x); 40 }else{ 41 cin >> x; 42 if(x == 0) 43 head = ne[head]; 44 remove(x - 1); 45 } 46 } 47 for(int i = head; i != -1; i = ne[i]) cout << e[i] << ' '; 48 return 0; 49 }