队列的特点
先入先出(FIFO)
队列之所以叫队列,就是因为它的这个特点。很像超市排队付款时排的队不是吗,前面不停地走,后面不停地跟上
在队列中,你也只能在最后面插入(insert),在最前面删除(delete)。插入操作也称作入队(enqueue), 删除操作也被称为出队(dequeue)
初步实现队列
如上所述,队列应支持两种操作:入队和出队(插入和删除)。
入队会向队列的末尾追加一个新元素,我们需要知道队列的末尾在哪;而出队会删除第一个元素。 所以我们需要知道队列的起点在哪。
实现如下:
class MyQueue {
private:
// store elements
vector<int> data;
// a pointer to indicate the start position
int p_start;
public:
MyQueue() {p_start = 0;}
/** Insert an element into the queue. Return true if the operation is successful. */
bool enQueue(int x) {
data.push_back(x);
return true;
}
/** Delete an element from the queue. Return true if the operation is successful. */
bool deQueue() {
if (isEmpty()) {
return false;
}
p_start++;
return true;
};
/** Get the front item from the queue. */
int Front() {
return data[p_start];
};
/** Checks whether the queue is empty or not. */
bool isEmpty() {
return p_start >= data.size();
}
};
int main() {
MyQueue q;
q.enQueue(5);
q.enQueue(3);
if (!q.isEmpty()) {
cout << q.Front() << endl;
}
q.deQueue();
if (!q.isEmpty()) {
cout << q.Front() << endl;
}
q.deQueue();
if (!q.isEmpty()) {
cout << q.Front() << endl;
}
}
这里我们用vector<int> data存储队列中的元素。用vector的好处是:前后元素是连着的,得到队列中一个元素的后一个元素很方便;在末尾添加元素很方便,只用push_back就可以;用一个表示下标的整数就可以轻易指向开头
除了插入和删除,注意到指向开头的下标还让我们能用q.Front()得到队列的第一个元素,用q.isEmpty()判断队列是否为空
上面的实现很简单,但在某些情况下空间利用率会很低。 要知道,vector里下标小于指向开头的下标的空间,在理论上是不存储队列元素的,那这些空间不就被浪费了吗?随着起始指针的移动,浪费了越来越多的空间。 当我们有空间限制时,这将是难以接受的。
如下图,head前面的那个空间就不存储任何的队列元素:
实际上,在这种情况下,我们应该能够再接受一个元素。
实现更高效的队列
上一节中,我们实现的队列会浪费空间,空间利用率低,现在我们想办法改进这一点
更有效的方法是使用循环队列。 具体来说,如果head前面有空间,那就在前面的空间里放元素,而不像上一节中不停地在后面索取空间
还是这张图,如果后面没有空间了,那用vector就没有办法push_back了,可是head前面明明还能再放下一个元素
实现如下:
class MyCircularQueue {
private:
vector<int> data;
int head;
int tail;
int size;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
data.resize(k);
head = -1;
tail = -1;
size = k;
}
/** Insert an element into the circular queue. Return true if the operation is
successful. */
bool enQueue(int value) {
if (isFull()) {
return false;
}
if (isEmpty()) {
head = 0;
}
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is
successful. */
bool deQueue() {
if (isEmpty()) {
return false;
}
if (head == tail) {
head = -1;
tail = -1;
return true;
}
head = (head + 1) % size;
return true;
}
/** Get the front item from the queue. */
int Front() {
if (isEmpty()) {
return -1;
}
return data[head];
}
/** Get the last item from the queue. */
int Rear() {
if (isEmpty()) {
return -1;
}
return data[tail];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return head == -1;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return ((tail + 1) % size) == head;
}
};
我建议仔细阅读上面的代码,最好自己画个带几个元素的队列出来
使用队列
因为队列很常用,所以大多数语言都提供内置的队列库,你没必要每次使用时都把上面的实现代码复制一遍
请熟悉一下push、empty、pop、front、size、back函数
#include <iostream>
#include <queue>
int main() {
// 1. Initialize a queue.
queue<int> q;
// 2. Push new element.
q.push(5);
q.push(13);
q.push(8);
q.push(6);
// 3. Check if queue is empty.
if (q.empty()) {
cout << "Queue is empty!" << endl;
return 0;
}
// 4. Pop an element.
q.pop();
// 5. Get the first element.
cout << "The first element is: " << q.front() << endl;
// 6. Get the last element.
cout << "The last element is: " << q.back() << endl;
// 7. Get the size of the queue.
cout << "The size is: " << q.size() << endl;
}
队列实现广度优先搜索(BFS)
BFS,常看题解的人应该都很眼熟,很多题目都可以用。其中,一个常见应用是找出从根结点到目标结点的最短路径
而BFS的实现,常常需要队列的参与
我们首先将根结点排入队列。然后在每一轮中,我们逐个处理已经在队列中的结点,并将所有邻居添加到队列中。值得注意的是,新添加的结点不会立即遍历,而是在下一轮中处理。
有的时候,一个结点不能被访问两次。如果是这样,我们可以添加一个哈希集来解决这个问题。
/**
* Return the length of the shortest path between root and target node.
*/
int BFS(Node root, Node target) {
queue<Node> queue; // store all nodes which are waiting to be processed
Unordered_set<Node> used; // store all the used nodes
int step = 0; // number of steps neeeded from root to current node
// initialize
add root to queue;
add root to used;
// BFS
while (queue.size()) {
step = step + 1;
// iterate the nodes which are already in the queue
int size = queue.size();
for (int i = 0; i < size; ++i) {
Node cur = the first node in queue;
if cur is target{
return step;
}
for (Node next : the neighbors of cur) {
if (next is not in used) {
add next to queue;
add next to used;
}
}
remove the first node from queue;
}
}
return -1; // there is no path from root to target
}
例题
200. 岛屿数量这一题理论上需要哈希集,有没有巧妙的办法不用呢?(提示:哈希集是为了标识那些访问过的结点)
752. 打开转盘锁难点只在于想到怎么由当前字符串得到下一组字符串,对字符串不熟悉的同学可能不知所措
279. 完全平方数对着上面的代码模板就能写出来