两栈实现队列,以及两队列实现栈

一。两栈实现队列
     栈s1是主栈,栈s2是辅助栈。题目的要求概括起来就是一句话:先进后出实现先进先出。
     对于入列操作enqueue(),直接采用s1的入栈操作push()即可。
     对于出列操作dequeue(),先把s1的数据pop()到s2中,此时s2中的数据与s1中的数据正好逆序,即s2的栈顶元素就是s1的栈底元素,也就是第一个入栈的数据,是我们需要返回的数据。暂存此数据方便返回。接着把s2中的数据依次返回到s1中即可。
代码:
//StacktoQueue.h
#ifndef STACKTOQUEUE_H_INCLUDED
#define STACKTOQUEUE_H_INCLUDED
#include <stack>

class StackToQueue{
    private:
        std::stack<int> s1;//s1是主栈
        std::stack<int> s2;//辅助栈
    public:
        void enqueue(int);
        int dequeue();
        int length();
        bool isEmpty();
};
#endif // STACKTOQUEUE_H_INCLUDED

//StacktoQueue.cpp
#include "StackToQueue.h"

void StackToQueue::enqueue(int i){//入列
    s1.push(i);
}

int StackToQueue::dequeue(){//出列
    while(!s1.empty()){//把s1中的数据都弹到s2中
        s2.push(s1.top());
        s1.pop();
    }
    int temp = s2.top();//返回s2的栈顶
    s2.pop();
    while(!s2.empty()){//再把剩余的数据返回到s1中
        s1.push(s2.top());
        s2.pop();
    }
    return temp;
}

int StackToQueue::length(){
    return s1.size();
}

bool StackToQueue::isEmpty(){
    return s1.empty();
}
//main.cpp
#include "StackToQueue.h"
#include <iostream>
using namespace std;

int main(){
    StackToQueue sq;
    for(int i = 0; i < 10; i++){
        sq.enqueue(i);
    }
    while(!sq.isEmpty()){
        cout << sq.dequeue() << endl;
    }
    return 0;
}

二、两队列实现栈
队列q1是主队列,q2是辅助队列。废话不说了,直接看代码吧,代码里有注释。。。
//QueueToStack.h
#ifndef QUEUETOSTACK_H_INCLUDED
#define QUEUETOSTACK_H_INCLUDED
#include <queue>
class QueueToStack{
    private:
        std::queue<int> q1;
        std::queue<int> q2;
    public:
        void push(int)二、两队列实现栈
队列q1是主队列,q2是辅助队列。废话不说了,直接看代码吧,代码里有注释。。。;
        int top();//返回栈顶元素,不删除
        void pop();//删除栈顶元素,不返回
        bool isEmpty();
};
#endif // QUEUETOSTACK_H_INCLUDED

//QueueToStack.cpp
#include "QueueToStack.h"

void QueueToStack::push(int i){
    q1.push(i);
}

int QueueToStack::top(){
    while(q1.size() != 1){//除了最后一个元素,其余的按原顺序放入q2
        q2.push(q1.front());
        q1.pop();
    }
    int temp = q1.front();//返回最后一个
    q2.push(q1.front());//最后一个入q2
    q1.pop();//清空q1
    while(!q2.empty()){//复原q1.
        q1.push(q2.front());
        q2.pop();
    }
    return temp;
}

void QueueToStack::pop(){
    while(q1.size() != 1){
        q2.push(q1.front());
        q1.pop();
    }
    q1.pop();
    while(!q2.empty()){
        q1.push(q2.front());
        q2.pop();
    }
}

bool QueueToStack::isEmpty(){
    return q1.empty();
}

//main.cpp
#include "QueueToStack.h"
#include <iostream>

int main(){
    QueueToStack qs;
    for(int i = 0;i < 10; i++){
        qs.push(i);
    }
    while(!qs.isEmpty()){
        std::cout << qs.top() << std::endl;
        qs.pop();
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值