模板描述:
数组模拟单链表
输出形式为 head–>1–>2–>3
深入理解:
add_to_head(3);
之后,e[0]=3,ne[0]=-1,链: (NULL<–)3<–head(<–idx)
add_to_head(2);
之后,ne[0]=-1,e[1]=2,ne[1]=0,链: (NULL<–)3<–2<–head(<–idx)
next[i]访问方向: <–
实际插入顺序: –>
head & idx增大/移动方向:–>
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int ,int> PII;
const int N=1e6+10;
int idx,e[N],ne[N],head;
int init()
{
head=-1;
idx=0;
}
int add_to_head(int x)
{
e[idx]=x; //值
ne[idx]=head; //next访问顺序为:head-->最后一个添加的元素-->...-->第一个添加的元素
head=idx; //新头设置为当前新结点,head向数字扩大方向移动
idx++; //idx向数字扩大方向移动
}
int main()
{
init(); //初始化
add_to_head(3); //头插入 3、2、1
add_to_head(2);
add_to_head(1);
cout<<"head-->";
for(int i=head;i>=0;i=ne[i]) //关键:从大到小输出
{
cout<<e[i];
if(ne[i]!=-1) //如果到了遍历最后一个元素(next为-1)
cout<<"-->";
}
return 0;
}
输出结果:
head-->1-->2-->3
Orz