数组实现单双链表的快速操作[时间复杂度为O(1)]
826. 单链表 - AcWing题库高质量的算法题库https://www.acwing.com/problem/content/828/
#include <iostream>
using namespace std;
const int N = 1e5+10;
int e[N],ne[N],head,idx;
int main()
{
int n,k,x;
char op;
head = -1, idx = 0;
cin >> n;
while (n -- )
{
cin >> op;
if(op == 'H'){
cin >> x;
e[idx] = x;
ne[idx] = head;
head = idx;
idx ++;
}else if(op == 'D'){
cin >> k;
if(!k) head = ne[head];
else ne[k-1] = ne[ne[k-1]];
}else if(op == 'I'){
cin >> k >> x;
e[idx] = x;
ne[idx] = ne[k-1];
ne[k-1] = idx;
idx ++;
}
}
for(int i = head;i != -1; i=ne[i]) cout << e[i] << ' ';
return 0;
}
827. 双链表 - AcWing题库高质量的算法题库https://www.acwing.com/problem/content/description/829/
#include <iostream>
using namespace std;
const int N = 1e5+10;
int l[N],r[N],e[N],head,idx;
void insert(int k, int x)
{
e[idx] = x;
l[idx] = k, r[idx] = r[k];
l[r[idx]] = idx, r[k] = idx++;
}
void del(int k)
{
l[r[k]] = l[k];
r[l[k]] = r[k];
}
int main()
{
int n,k,x;
cin >> n;
string op;
l[1] = 0,r[0] = 1;
idx = 2;
while (n -- )
{
cin >> op;
if(op == "L"){
cin >> x;
insert(0, x);
}
else if(op == "R"){
cin >> x;
insert(l[1], x);
}
else if(op == "D"){
cin >> k;
del(k+1);
}
else if(op == "IL"){
cin >> k >> x;
insert(l[k+1], x);
}
else if(op == "IR"){
cin >> k >> x;
insert(k+1, x);
}
}
for (int i = r[0]; i != 1; i=r[i]) cout << e[i] << ' ';
return 0;
}
本文来自博客园,作者:泥烟,CSDN同名, 转载请注明原文链接:https://www.cnblogs.com/Knight02/p/15799075.html