算法之由两个栈组成队列

题目

编写一个类,用两个栈实现队列,支持队列的基本操作(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++语言知识有限,请见谅~ ~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值