In this C++ code I'm implementing Queue
with a Single stack
instance. I found this code in GeeksForGeeks. Url Here
#include <bits/stdc++.h>
using namespace std;
class Queue
{
private:
stack<int> s;
public:
void enque(int x)
{
s.push(x);
}
int deque()
{
if (s.empty())
{
cout << "Q is empty" << endl;
return -1;
}
int x = s.top();
s.pop();
if (s.empty())
{
return x;
}
// I'm not able to understand these 3 lines after this comment
int item = deque();
s.push(x);
return item;
}
};
int main()
{
Queue q;
q.enque(1);
q.enque(2);
q.enque(3);
cout << "Output: " << q.deque() << endl;
cout << "Output: " << q.deque() << endl;
cout << "Output: " << q.deque() << endl;
cout << "Output: " << q.deque() << endl;
return 0;
}
But I cannot understand these 3 lines
int item = deque();
s.push(x);
return item;
Problem
How after calling deque() recursively the compiler reaches the next lines to push x
again to the stack. And how it is retaining the value of x after recursive function call.
The code isn't really using a single stack, its using the built-in stack as a second stack via the recursive call to deque
. The code is equivalent to:
#include <iostream>
#include <stack>
class Queue
{
private:
std::stack<int> s;
public:
void enque(int x)
{
s.push(x);
}
int deque()
{
if (s.empty())
{
std::cout << "Q is empty\n";
return -1;
}
std::stack<int> temp;
while (s.size() != 1)
{
temp.push(s.top());
s.pop();
}
int result = s.top();
s.pop();
while (!temp.empty())
{
s.push(temp.top());
temp.pop();
}
return result;
}
};
int main()
{
Queue q;
q.enque(1);
q.enque(2);
q.enque(3);
std::cout << "Output: " << q.deque() << "\n";
std::cout << "Output: " << q.deque() << "\n";
std::cout << "Output: " << q.deque() << "\n";
std::cout << "Output: " << q.deque() << "\n";
return 0;
}
I can't think of a reason you'd implement a queue this way, as the queue grows in size deque
gets more and more expensive, using the original code you'd ultimately end up with a stack overflow. If you need a queue use std::queue
or std::deque
(by default std::queue
is just a wrapper round std::deque
which hides the push_front
/ pop_back
methods)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.