【数组模拟单链表】
用两个数组 e[]、ne[] 模拟单链表。
例如:语句 e[id]=key, ne[id]=next; 可以模拟位于地址 id 的结点。其中,e[id]=key 表示地址 id 位置处的结点值为 key,ne[id]=next 表示地址 id 位置处的结点的下一个结点位置为 next。
下面代码模拟了单链表:18 → 7 → -4 → 0 → 5 → -6 → 10 → 11 → -2,其中测试样例中的地址 id 是随意给的,但要保证各个结点能够通过 id 连接起来,且要注意尾结点的 next 值为 -1。
【算法代码】
#include <bits/stdc++.h>
using namespace std;const int maxn=1e5+5;
int e[maxn],ne[maxn];
int head,n;int main() {cin>>head>>n;while(n--) {int id,key,next;cin>>id>>key>>next;e[id]=key, ne[id]=next;}vector<int> v;for(int i=head; i!=-1; i=ne[i]) {v.push_back(i);}for(int i=0; i<v.size(); i++) {printf("%05d %d ",v[i],e[v[i]]);if(i==v.size()-1) cout<<"-1"<<endl;else printf("%05d\n",v[i+1]);}return 0;
}/*
in:
00100 9
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218out:
00100 18 12309
12309 7 33218
33218 -4 00000
00000 0 99999
99999 5 68237
68237 -6 23333
23333 10 27777
27777 11 48652
48652 -2 -1
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/143686676