How to reverse a queue?
How can I write a reverse function using enqueue and dequeue?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
template <class T>
void Dynque<T>::enqueue(T num)
{
QueueNode *newNode;
newNode = new QueueNode;
newNode->value = num;
newNode->next = NULL;
if (isEmpty())
front = rear = newNode;
else
{
rear->next = newNode;
rear = newNode;
}
numItems++;
}
template <class T>
void Dynque<T>::dequeue(T &num)
{
QueueNode *temp;
if (isEmpty())
cout << "The queue is empty.\n";
else
{
num = front->value;
temp = front->next;
delete front;
front = temp;
numItems--;
}
}
|
Thanks in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
template <typename T>
void reverse(Dynque<T> queue)
{
std::stack<T> temp_storage;
while (not queue.isEmpty()) {
T val;
queue.dequeue(val);
temp_storage.push(val);
}
while (not temp_storage.empty()) {
queue.enqueue(temp_storage.top());
temp_storage.pop();
}
}
|
Topic archived. No new replies allowed.