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?
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
headandtailrather 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.