1.单链表【数组模拟链式存储结构】
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int e[N],ne[N];
int head,idx;
void init()
{
head=-1;
idx=0;
}
void add_to_head(int x)
{
e[idx]=x;
ne[idx]=head;
head=idx;
idx++;
}
void add(int k,int x)
{
e[idx]=x;
ne[idx]=ne[k];
ne[k]=idx;
idx++;
}
void removee(int k)
{
ne[k]=ne[ne[k]];
}
int main()
{
int m;
int x,k;
char op;
cin>>m;
init();
while(m--)
{
cin>>op;
if(op=='H')
{
cin>>x;
add_to_head(x);
}
else if(op=='I')
{
cin>>k>>x;
add(k-1,x);
}
else if(op=='D')
{
cin>>k;
if(!k) head=ne[head];
removee(k-1);
}
}
for(int i=head;i!=-1;i=ne[i])
printf("%d ",e[i]);
return 0;
}
2.双链表
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int l[N],r[N],e[N],idx;
void init()
{
l[1]=0;
r[0]=1;
idx=2;
}
void add(int k,int x)
{
e[idx]=x;
r[idx]=r[k];
l[idx]=k;
l[r[k]]=idx;
r[k]=idx;
idx++;
}
void removee(int k)
{
r[l[k]]=r[k];
l[r[k]]=l[k];
}
int main()
{
string op;
int m,x,k;
cin>>m;
init();
while(m--)
{
cin>>op;
if(op=="L")
{
cin>>x;
add(0,x);
}
if(op=="R")
{
cin>>x;
add(l[1],x);
}
if(op=="D")
{
cin>>k;
removee(k+1);
}
if(op=="IL")
{
cin>>k>>x;
add(l[k+1],x);
}
if(op=="IR")
{
cin>>k>>x;
add(k+1,x);
}
}
for(int i=r[0];i!=1;i=r[i])
printf("%d ",e[i]);
printf("\n");
return 0;
}
3.模拟栈【数组模拟】
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int stk[N],tt;
void init()
{
tt=-1;
}
void push(int x)
{
tt++;
stk[tt]=x;
}
void pop()
{
tt--;
}
void emptyy()
{
if(tt==-1) printf("YES\n");
else printf("NO\n");
}
void query()
{
printf("%d\n",stk[tt]);
}
int main()
{
int m,x;
string op;
cin>>m;
init();
while(m--)
{
cin>>op;
if(op=="push")
{
cin>>x;
push(x);
}
if(op=="query")
{
query();
}
if(op=="pop")
{
pop();
}
if(op=="empty")
{
emptyy();
}
}
return 0;
}
4.模拟队列【数组模拟】
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int q[N],h,t;
void init()
{
h=0;
t=0;
}
void push(int x)
{
q[t]=x;t++;
}
void pop()
{
h++;
}
void emptyy()
{
if(h==t) printf("YES\n");
else printf("NO\n");
}
void query()
{
printf("%d\n",q[h]);
}
int main()
{
init();
int m,x;
string op;
cin>>m;
while(m--)
{
cin>>op;
if(op=="push")
{
cin>>x;
push(x);
}
if(op=="query")
{
query();
}
if(op=="pop")
{
pop();
}
if(op=="empty")
{
emptyy();
}
}
return 0;
}
5.单调栈
#include <bits/stdc++.h>
using namespace std;
const int N=10010;
int stk[N],tt=0;
int main()
{
int n,x;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x;
while(tt&&stk[tt]>=x) tt--;
if(tt) printf("%d ",stk[tt]);
else printf("-1 ");
tt++;
stk[tt]=x;
}
return 0;
}
6.单调队列【滑动窗口】
#include <bits/stdc++.h>
using namespace std;
const int N=1000010;
int a[N],q[N];
int main()
{
int n,k;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
int hh=0,tt=-1;
for(int i=0;i<n;i++)
{
if(hh<=tt&&i-k+1>q[hh]) hh++;
while(hh<=tt&&a[q[tt]]>=a[i]) tt--;
q[++tt]=i;
if(i>=k-1) printf("%d ",a[q[hh]]);
}puts("");
hh=0,tt=-1;
for(int i=0;i<n;i++)
{
if(hh<=tt&&i-k+1>q[hh]) hh++;
while(hh<=tt&&a[q[tt]]<=a[i]) tt--;
q[++tt]=i;
if(i>=k-1) printf("%d ",a[q[hh]]);
}puts("");
return 0;
}