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.