上面代码不使用#include <queue> #include <unordered_map>,来实现
时间: 2023-12-28 14:06:00 浏览: 90
那么可以使用手动实现队列和哈希表来代替STL中的queue和unordered_map。
队列可以使用数组或链表来实现,这里以数组为例:
```cpp
const int MAXN = 1e5; // 队列最大容量
int q[MAXN], front = 0, rear = -1;
bool empty() {
return front > rear;
}
void push(int x) {
q[++rear] = x;
}
void pop() {
++front;
}
int front() {
return q[front];
}
```
哈希表可以使用数组或链表来实现,这里以数组为例:
```cpp
const int MAXN = 1e6; // 哈希表最大容量
int h[MAXN], idx = 0;
void insert(int x) {
int pos = (x % MAXN + MAXN) % MAXN; // 计算哈希值
for (int i = h[pos]; i != -1; i = e[i].next) { // 遍历链表
if (e[i].key == x) return; // 已经存在
}
e[idx].key = x; // 插入新节点
e[idx].next = h[pos];
h[pos] = idx++;
}
bool find(int x) {
int pos = (x % MAXN + MAXN) % MAXN; // 计算哈希值
for (int i = h[pos]; i != -1; i = e[i].next) { // 遍历链表
if (e[i].key == x) return true; // 找到了
}
return false; // 没有找到
}
```
这里需要注意的是,要实现一个完整的哈希表,还需要定义一个节点结构体`struct Node { int key, next; } e[MAXN]`来存储节点信息,其中`key`表示键值,`next`表示指向下一个节点的指针。同时,初始化哈希表时需要将所有的`h[i]`初始化为-1,表示链表为空。
阅读全文
相关推荐


















