【发布时间】:2021-09-09 21:09:54
【问题描述】:
在这个 C++ 代码中,我使用单个 stack 实例来实现 Queue。
我在 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;
}
但我无法理解这 3 行
int item = deque();
s.push(x);
return item;
问题
在递归调用 deque() 之后,编译器如何到达下一行以将 x 再次推送到堆栈。以及如何在递归函数调用后保留 x 的值。
【问题讨论】:
-
忘记 gfg 垃圾收集,除非您想学习如何编写非常糟糕的 C++ 代码。 Why should I not
#include <bits/stdc++.h>?Why isusing namespace std;considered bad practice? -
在 调试器 中运行代码,并见证变量的修改及其内容。如果您考虑在使用可以选择使用的最糟糕的后端容器(堆栈)实现队列时戴上什么手铐,这也会有所帮助。一支铅笔、一张纸和一些唯一可能的算法的手动迭代就很能说明问题了。
-
deque的每个递归调用都使用内存中的不同位置来存储局部变量的值。该内存用于存储x的值。 -
你应该小心 geeksforgeeks 上的东西。主要是尽量避免它。在许多情况下,它会教授非常非常糟糕的编程实践。 C++ stl 提供了更有效的用法。std::queue 可能会以更好的方式满足您的目的。在您的示例中,您基本上是递归清空堆栈并在底部返回东西。
-
如果您认为您并没有真正使用单个堆栈,那么代码可能更容易理解,您还使用内置堆栈来临时存储值。可以肯定地说,这是一种非常低效的队列实现方式,请使用适当的队列数据结构