用两个栈实现一个队列,实现队列的push和pop操作
栈的特性是先进后出(FILO),队列的特性是先进先出(FIFO),在实现pop时,我们的难点是如何将栈中最底层的数据拿出来,我们有两个栈,所以我们可以将一个栈中的数据依次拿出来压入到另一个为空的栈,另一个栈中数据的顺序恰好是先压入栈1的元素此时在栈2的上面,为了实现效率的提升,我们在pop时,判断栈2是否有数据,如果有的话,直接删除栈顶元素,在栈2为空时才将栈1的数据压入到栈2中,从而提高程序的运行效率,实现过程可以分为下面几个步骤:
1、push操作时,一直将数据压入到栈2中
2、pop操作时,首先判断栈2是否为空,不为空的情况直接删除栈2栈顶元素,为空的话将栈1的数据压入到栈2中,再将栈2栈顶元素删除。
#include<iostream>
#include<stack>
#include<assert.h>
using namespace std;
class Queue
{
stack<int> stack1;
stack<int> stack2;
public:
//入队列
void push(const int&data){
stack1.push(data);
}
//出队列
void Pop()
{
//如果两个栈都是空栈,此时说明队列是空的
if (stack1.empty() && stack2.empty())
cout << "this queue is empty" << endl;
//如果栈2中有元素,那出队列就出栈2中的
if (!stack2.empty()){
stack2.pop();
}
//此时表明栈2已是空栈,再要出队列的话,那就需要把栈1中的所有元
//素入栈到栈2中,注意一定要是栈1中的所有元素都入栈到栈2中
else{
while (stack1.size() > 0){
stack2.push(stack1.top());
stack1.pop();
}
stack2.pop();
}
}
int Front()//获取队头元素,此时队头位于栈2的栈顶
{
assert(!stack1.empty() || !stack2.empty());
if (stack2.empty()){
while (!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
return stack2.top();
}
};
void TestQueue()
{
Queue q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);;
cout << "队头为: " << q.Front() << endl;
q.Pop();
q.Pop();
cout << "队头为: " << q.Front() << endl;
q.push(5);
q.Pop();
cout << "队头为: " << q.Front() << endl;
}
int main()
{
TestQueue();
system("pause");
return 0;
}

被折叠的 条评论
为什么被折叠?



