题目
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。
解决方案
根据栈的特点:先进后出。如果要想使用两个栈实现队列(先入先出特点)。只需要定义两个栈,分别命名为input和output。当input 表示入队,而output表示出队。关键点在于,只要当input中的元素要一次弹栈并压入output栈中。并且只要output中元素全出弹出后,才能够再次重复此操作
具体代码如下所示:
//-------------- FILE QList.hpp -----------------
#ifndef QList_hpp
#define QList_hpp
#include <stdio.h>
#include <stack>
using namespace std;
class QList{
private:
stack<int>* input;
stack<int>* output;
void i2o();
void checkEmpty();
public:
QList();
~QList();
void add(int);
int poll();
int peek();
};
#endif /* QList_hpp */
方法实现:
//-------------- FILE QList.hpp -----------------
#include "QList.hpp"
QList::QList(){
input = new stack<int>();
output = new stack<int>();
}
QList::~QList(){
delete input;
delete output;
}
void QList::i2o(){
if(this->output->empty()){
//复制元素,从input到output
while (!this->input->empty()) {
int e = this->input->top();
this->output->push(e);
this->input->pop();
}
}
}
void QList::add(int e){
this->input->push(e);
this->i2o();
}
int QList::peek(){
checkEmpty();
i2o();
return this->output->top();
}
int QList::poll(){
checkEmpty();
i2o();
int e = this->output->top();
this->output->pop();
return e;
}
void QList::checkEmpty(){
if(this->input->empty()&&this->output->empty()){
throw invalid_argument("QList is empty !!!");
}
}
测试代码:
int main(int argc, const char * argv[]) {
QList* list = new QList();
list->add(1);
list->add(9);
list->add(7);
cout<< list->poll() << " " << list->poll() << " " << list->poll() << endl;
return 0;
}
由于C++语言知识有限,请见谅~ ~