手搓单链表【数组模拟】

单链表不会数组模拟的参考此博客:https://blog.csdn.net/Satur9/article/details/104072845?depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1&utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1



image



数据结构中单链表模板题


上代码:

  1 #include <iostream>
  2 #include <algorithm>
  3 #include <cstring>
  4 
  5 using namespace std;
  6 
  7 int head = -1;//头指针,假设为指向空
  8 int dat[100010];//储存值
  9 int nex[100010];//储存指针
 10 int idx = 0;
 11 void add_to_head(int x) { // 将x插入到头节点后面
 12 	dat[idx] = x;
 13 	nex[idx] = head;
 14 	head = idx ++;
 15 }
 16 void add(int k, int x) { //将x插入到第k个结点之后
 17 	dat[idx] = x;
 18 	nex[idx] = nex[k];
 19 	nex[k] = idx++;
 20 }
 21 
 22 void remove(int k) {//删除第k个结点
 23 	nex[k] = nex[nex[k]];
 24 }
 25 
 26 int main() {
 27 	int m;
 28 	cin >> m;
 29 	while (m--) {
 30 		int k, x;
 31 		char op;
 32 		cin >> op;
 33 		if (op == 'H') {
 34 			cin >> x;
 35 			add_to_head(x);
 36 		}
 37 		else if (op == 'D') {
 38 			cin >> k;
 39 			if (!k) head = nex[head];
 40 			remove(k - 1);
 41 		}
 42 		else {
 43 			cin >> k >> x;
 44 			add(k - 1, x);
 45 		}
 46 	}
 47 	for (int i = head; i != -1; i = nex[i])
 48 		cout << dat[i] << " ";
 49 	cout << endl;
 50 
 51 	return 0;
 52 }



追求吾之所爱
原文地址:https://www.cnblogs.com/rstz/p/14391023.html