链表
Huangwenqi · · 算法·理论
数组: 访问快(
1. 指针链表
详见
2. 静态链表
单向
const int N=1e6+010;
struct List{
int v,nxt;
}a[N];
int h=1,tot=1;
void insert_after(int i,int v){
a[++tot]={v,a[i].nxt};
a[i].nxt=tot;
}
双向
const int N=5e5+010;
struct List{
int v;
int lst,nxt;
}a[N];
int h,tot;
void clr(){
tot=0;
a[h]={0,-1,-1};
}
int fd(int x){
for(int i=a[h].nxt;~i;i=a[i].nxt)
if(a[i].v==x) return i;
return -1;
}
void insert_after(int v){
int i=h;
a[++tot]={v,i,a[i].nxt};
a[a[i].nxt].lst=tot;
a[i].nxt=tot;
}
void insert_after(int i,int v){
a[++tot]={v,i,a[i].nxt};
a[a[i].nxt].lst=tot;
a[i].nxt=tot;
}
void insert_before(int i,int v){
a[++tot]={v,a[i].lst,i};
a[a[i].lst].nxt=tot;
a[i].lst=tot;
}
void list_erase(int i){
a[a[i].nxt].lst=a[i].lst;
a[a[i].lst].nxt=a[i].nxt;
}
\color{black}\bold{B3631\ 单向链表}
思路
如题目描述。 :::info[代码]
#include<iostream>
using namespace std;
const int N=1e6+010;
struct List{
int v,nxt;
}a[N];
int b[N];
int h=1,tot=1;
void insert_after(int i,int v){
a[++tot]={v,a[i].nxt};
a[i].nxt=tot;
b[v]=tot;
}
void list_erase(int i){
a[i].nxt=a[a[i].nxt].nxt;
}
int q;
int main(){
cin>>q;
a[1]={1,0};
b[1]=1;
while(q--){
int ch,x;
cin>>ch>>x;
if(ch==1){
int y;
cin>>y;
insert_after(b[x],y);
}
else if(ch==2) cout<<a[a[b[x]].nxt].v<<'\n';
else list_erase(b[x]);
}
return 0;
}
:::
\color{black}\bold{B4324\ 【模板】双向链表}
思路
如题目描述。 :::info[代码]
#include<iostream>
#include<stack>
using namespace std;
const int N=5e5+010;
struct List{
int v;
int lst,nxt;
}a[N<<1];
int b[N];
int h,tot;
void clr(){
tot=0;
a[h]={0,-1,-1};
}
int fd(int x){
for(int i=a[h].nxt;~i;i=a[i].nxt)
if(a[i].v==x) return i;
return -1;
}
void add_back(int v){
int i=h;
a[++tot]={v,i,a[i].nxt};
a[a[i].nxt].lst=tot;
a[i].nxt=tot;
b[v]=tot;
}
void insert_after(int i,int v){
a[++tot]={v,i,a[i].nxt};
a[a[i].nxt].lst=tot;
a[i].nxt=tot;
b[v]=tot;
}
void insert_before(int i,int v){
a[++tot]={v,a[i].lst,i};
a[a[i].lst].nxt=tot;
a[i].lst=tot;
b[v]=tot;
}
void list_erase(int i){
b[a[i].v]=0;
a[a[i].nxt].lst=a[i].lst;
a[a[i].lst].nxt=a[i].nxt;
}
int n,m;
stack<int>st;
int main(){
clr();
cin>>n>>m;
for(int i=1;i<=n;i++)
add_back(i);
while(m--){
int ch,x;
cin>>ch>>x;
if(ch==1||ch==2){
int y;
cin>>y;
if(x==y) continue;
if(b[x]) list_erase(b[x]);
if(ch==1) insert_after(b[y],x);
else insert_before(b[y],x);
}
else if(b[x]) list_erase(b[x]);
}
for(int i=a[h].nxt;~i;i=a[i].nxt)
st.push(a[i].v);
if(!st.size()) cout<<"Empty!";
while(st.size()){
cout<<st.top()<<' ';
st.pop();
}
return 0;
}
:::