使用数组实现简单的队列
我对数组、队列和堆栈了解不多。我知道如何实现一个简单的队列。
#include <iostream>
#include <queue>
using namespace std;
void main()
{
queue<char> queue1;
queue1.push('a');
queue1.push('b');
queue1.push('c');
queue1.push('d');
while(!queue1.empty())
{
cout << queue1.front();
queue1.pop();
cout << endl;
}
system("pause");
}
如何使用数组实现简单的队列?
I don't know much about arrays and queues and stacks. I know how to implement a simple queue.
#include <iostream>
#include <queue>
using namespace std;
void main()
{
queue<char> queue1;
queue1.push('a');
queue1.push('b');
queue1.push('c');
queue1.push('d');
while(!queue1.empty())
{
cout << queue1.front();
queue1.pop();
cout << endl;
}
system("pause");
}
How can I implement a simple queue using an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的队列基于数组,那么为了提高效率,我建议创建一个有界或“循环”队列,其中队列的最大大小是固定的,并且您基本上有一个指向队列数组中的“第一个”和“最后一个”位置,当尾指针(或索引值)移动到“过去”数组末尾的位置时,它实际上移回到数组的开头。基于数组的无界队列效率非常低,因为每次填满数组的最大大小时都需要重新分配内存,和/或在删除第一个元素时尝试重新排列数组中的元素队列的元素。
对
head
和tail
使用整型数组索引,而不是实际的指针类型,并使用计数器来确定队列中的项目总数、入队和出队函数看起来很简单:您可以将这个概念扩展到您想要的任何其他函数,即,如果您希望有一个单独的函数,例如 STL 用于访问队列头并实际上从队列中“删除”元素队列。
If your queue is based on an array, then for efficiency's sake, I would recommend creating a bounded or "circular" queue, where the max-size of the queue is fixed, and you basically have a head and tail pointer that point to the "first" and "last" positions in the queue's array, and when the tail-pointer (or an index value) moves to a position "past" the end of the array, it actually moves back to the beginning of the array. An unbounded queue based on an array would be horribly inefficient, as you would need to keep reallocating memory each time you fill up the max-size of the array, and/or attempt to re-shuffle elements down the array when you remove the first element of the queue.
Using integral-type array indexes for
head
andtail
rather than actual pointer types, along with a counter for determining the overall number of items in your queue, your enqueue and dequeue functions could look as simple as:You can extend this concept to whatever other functions you'd like, i.e., if you'd rather have a separate functions like the STL uses for accessing the head of the queue and actually "removing" an element from the queue.
注意:在将数组(线性数据存储)模拟为循环数据存储并保持队列属性时,总会有一个单元格未被使用。因此,对于具有 6 个单元的阵列,阵列的最大容量将为 5。下面的 C++ 代码是不言自明的。另请参阅队列的基于链表的实现。
可以在此处观看相同的视频教程:数据结构:队列的数组实现
NOTE: While simulating an array(linear data storage) as a circular data storage and maintaining the properties of Queue, one cell will always be unused. Hence, the maximum capacity of array will be 5 for the array having 6 cells. The c++ code below is self explanatory. Also, see The Linked List Based Implementation of Queue.
A video tutorial of the same can be seen here : Data structures: Array implementation of Queue