数据结构 |
变量 |
初始化 |
备注 |
单链表 |
int head, e[N], ne[N], idx; |
head = -1; idx = 0; |
删除操作头结点的特判; idx 从0 开始,第k个下标为 k-1 |
双链表 |
int head, e[N], ne[N], idx; |
r[0] = 1; l[1] = 0; idx = 2; |
idx 从2 开始,第k个下标为K+1 |
栈 |
int stk[N], tt ; |
tt = 0; |
void pop() 注意对tt的下标合法性判断 |
队列 |
int q[N], hh, tt; |
hh = 0; tt = -1; |
|
#include <iostream>
using namespace std;
const int N = 100010;
int head, e[N], ne[N], 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 remove(int k)
{
ne[k] = ne[ne[k]];
}
int main()
{
int m;
cin >> m;
init();
while(m --)
{
int k ,x;
char op;
cin >> op;
if(op == 'H')
{
cin >> x;
add_to_head(x);
}
else if(op == 'D')
{
cin >> k ;
if(!k) head = ne[head];
remove(k - 1);
}
else
{
cin >> k >> x;
add(k -1 , x);
}
}
for(int i = head; i != -1; i = ne[i])
cout << e[i] << ' ';
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int m;
int e[N],l[N],r[N],idx;
void init()
{
r[0] = 1;
l[1] = 0;
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 remove(int k)
{
r[l[k]] = r[k];
l[r[k]] = l[k];
}
int main()
{
cin >> m;
init();
while(m --)
{
int k ,x;
string op;
cin >> op;
if(op == "L")
{
cin >> x ;
add(0, x);
}
else if (op == "R")
{
cin >> x ;
add(l[1], x);
}
else if (op == "D")
{
cin >> k ;
if(!k)
{
r[0] = 1;
l[1] = 0;
}
remove(k + 1);
}
else if (op == "IL")
{
cin >> k >> x;
add(l[k + 1], x);
}
else
{
cin >> k >> x;
add(k + 1, x);
}
}
for(int i = r[0] ; i != 1; i = r[i])
cout << e[i] << ' ';
return 0;
}
#include <iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int stk[N], tt;
void push(int x)
{
stk [++ tt] = x;
}
void pop ()
{
if(tt) tt --;
}
bool empty()
{
return tt == 0;
}
int query()
{
return stk[tt];
}
int main()
{
int m;
cin >> m;
while(m--)
{
string op;
int x;
cin >> op;
if(op == "push")
{
cin >> x;
push(x);
}
else if(op == "pop")
{
pop();
}
else if(op == "empty")
{
cout << (empty() ? "YES" :"NO") << endl;
}
else
{
cout << query() << endl;
}
}
return 0;
}
#include <iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int q[N], hh, tt = -1;
void push(int x)
{
q [++ tt] = x;
}
void pop ()
{
hh ++;
}
bool empty()
{
return hh > tt;
}
int query()
{
return q[hh];
}
int main()
{
int m;
cin >> m;
while(m--)
{
string op;
int x;
cin >> op;
if(op == "push")
{
cin >> x;
push(x);
}
else if(op == "pop")
{
pop();
}
else if(op == "empty")
{
cout << (empty() ? "YES" :"NO") << endl;
}
else
{
cout << query() << endl;
}
}
return 0;
}
大佬那个 单链表删头结点的时候k=0 不就remove(-1) 了吗 访问数组下标没负数啊..