【刷题模板】链表、堆栈
算法模板
- 单链表
- 双链表
- 栈
- 队列
- 1. 普通队列
- 2. 循环队列
- 单调栈
- 单调队列
单链表
int head, e[N], ne[N], idx;void init()
{head = -1;idx = 0;
}void insert(int a)
{e[idx] = a, ne[idx] = head, head = idx++;
}
void remove()
{head = ne[head]
}
双链表
int e[N], l[N], r[N], idx;void init()
{r[0] = 1, l[1] = 0;idx = 2;
}void insert(int a, int x)
{e[idx] = x;l[idx] = a, r[idx] = r[a]; // a是指针;l[r[a]] = idx, r[a] = idx++; // idx是插入节点的指针;
}void remove(int a)
{l[r[a]] = l[a]; // r[a]表示a右节点的指针;r[l[a]] = r[a];
}
栈
int stk[N], tt = 0;
stk[++tt] = x;
tt--;
stk[tt];
if (tt > 0)
{}
队列
1. 普通队列
int q[N], hh = 0, tt = -1;
q[++tt] = x;
hh ++;
q[hh];if (hh <= tt)
{}
2. 循环队列
int q[N], hh = 0, tt = 0;
q[tt++] = x;
if (tt == N) tt = 0;hh++;
if (hh == N) hh = 0;q[hh];if (hh != tt)
{}
单调栈
数列:3 4 2 7 5
-1 3 -1 2 2
先考虑暴力做法,然后再优化;
数列: a1, a2, a3, … an;
if x < y
且,a(x) > a(y), 则a(x)永远不会被取到(不会被放入单调栈中);
if std[tt] >= a(i)
tt–;
常见模型:找出每个数左边离它最近的比它大/小的数;
int tt = 0;
for (int i = 1; i <= n; i++)
{while (tt && check(std[tt], i)) tt--;stk[++tt] = i;
}
单调队列
常见模型: 找出滑动窗口中最大、最小值
int hh = 0, tt = -1;
for (int i = 0; i < n; i++)
{while (hh <= tt && check_out(q[hh]) hh++;while (hh <= tt && check(q[tt], i)) t--;q[++tt] = i;
}