【发布时间】:2020-04-30 01:15:27
【问题描述】:
我正在尝试使用堆栈和递归调用来实现队列,这是 Stack 类和一些方法:
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class Node{
public:
int data;
Node* next;
};
Node* top = NULL;
void push(int data){
Node* node = new Node();
node->data = data;
node->next = top;
top = node;
cout << "pushato: " << node->data << "\n";
};
bool isempty(){
if(top==NULL){
return true;
}else{
return false;
}
};
void pop(){
if(isempty()){
cout << "lo stack e vuoto.\n";
}else{
Node* ptr = top;
top = top->next;
cout << "eliminato: " << ptr->data << "\n";
delete(ptr);
}
};
Node* showtop(){
if(!isempty()){
cout << "l'elemento del top e: " << top->data << "\n";
return top;
}else{
cout << "lo stack e vuoto.\n";
}
};
这是队列的结构:
struct Queue{
void enQueue(int x)
{
push(x);
}
int deQueue()
{
if (isempty()) {
cout << "Q is empty";
exit(0);
}
// pop an item from the stack
int x = showtop()->data;
pop();
// if stack becomes empty, return
// the popped item
if (isempty()){
return x;
}
// recursive call
int item = deQueue();
// push popped item back to the stack
push(x);
// return the result of deQueue() call
return item;
}
};
这是主要的:
int main(int argc, char** argv) {
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
return 0;
}
这是输出:
pushed:1
pushed:2
pushed:3
popped 3
popped 2
popped 1
pushed 2
pushed 3
1
popped 3
popped 2
pushed 3
2
popped 3
3
代码工作正常,输出完全正确,但我真的不明白为什么在递归调用结束后我在 if 中返回 x,之前的所有项目都被推入堆栈? push(x)如何再次将项目添加到堆栈中,没有底部的元素?
【问题讨论】:
标签: c++ recursion data-structures stack queue