准备两个栈,一个是压入栈,一个是d出栈。
每次 *** 作时,看看d出栈是否为空,为空时,将压入栈的数据全放入d出栈。
/*==============================================================*
* Copyright (C) All rights reserved.
*
* 文件名称:
* 创 建 者:徐永琪
* 创建日期:2022年04月01年
* 描 述:两个栈实现队列
*
================================================================*/
#include
#include
/*by xuyongqi*/
using namespace std;
class two_stacks_implement_queue
{
private:
stack<int> stack_push;
stack<int> stack_pop;
void push_to_pop();
public:
void push(int data);
void pop();
int top();
bool empty();
};
void two_stacks_implement_queue::push_to_pop()
{
/*当d出栈为空时,把压入栈的数据全放入d出栈*/
if (stack_pop.empty())
{
while (!stack_push.empty())
{
stack_pop.push(stack_push.top());
stack_push.pop();
}
}
}
void two_stacks_implement_queue::push(int data)
{
stack_push.push(data);
push_to_pop();
}
void two_stacks_implement_queue::pop()
{
push_to_pop();
stack_pop.pop();
}
int two_stacks_implement_queue::top()
{
push_to_pop();
return stack_pop.top();
}
bool two_stacks_implement_queue::empty()
{
return stack_push.empty() && stack_pop.empty();
}
int main()
{
two_stacks_implement_queue *q = new two_stacks_implement_queue;
q->push(1);
q->push(2);
q->push(3);
q->push(4);
q->push(5);
while (!q->empty())
{
cout<<" top :"<<q->top()<<endl;
q->pop();
}
delete q;
q = nullptr;
return 0;
}
/* print
top :1
top :2
top :3
top :4
top :5
*/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)