引言
首先看这个标题的时候,需要联想到栈和队列的特点,栈是先进后出,队列是先进先出。假如三个元素1,2,3,将这三个元素依次入栈1后,再将栈1中元素依次出栈放入到栈2中,栈1中只留下最后一个元素1,此时栈2中由两个元素,接下来获取栈1中的栈顶元素,就类似于获取队列中的队顶元素,而此时从栈1中调用出栈,就类似于队列中的出队,将栈2中的元素入栈栈1,获取栈1中的栈顶元素,就类似于获取队列的队尾元素。以上是实现的思维过程。
示例
下面将具体的实现代码附上。
#include <iostream>
#include <stdio.h>
#include <stack>
using namespace std;//两个栈实现一个队列
/***************************************
实现思想:将元素存入栈1中;将栈1中的元素除第一个元素外其它元素出栈将栈1中的元素出栈后入栈栈2将栈1中栈底元素,直接出栈(模拟队列的队头删除元素)返回栈1中栈底元素(模拟队列获取对头元素)返回栈1的栈顶元素(模拟获取队列队尾的元素)===============================================功能:队列的出队,入队,获取对头元素,队尾元素;
****************************************/
class queueCustom
{
public:void push(int num)//入队{m_stack1.push(num);}int back()//队尾{return m_stack1.top();}int front()//队头{while (m_stack1.size() > 1){m_stack2.push(m_stack1.top());m_stack1.pop();}int frontElement = m_stack1.top();while (m_stack2.size() != 0){m_stack1.push(m_stack2.top());m_stack2.pop();}return frontElement;}void pop()//出队{while (m_stack1.size() > 1){m_stack2.push(m_stack1.top());m_stack1.pop();}m_stack1.pop();while (m_stack2.size() != 0){m_stack1.push(m_stack2.top());m_stack2.pop();} }
protected:
private:stack<int> m_stack1;stack<int> m_stack2;
};int _tmain(int argc, _TCHAR* argv[])
{queueCustom myQueue;myQueue.push(1);//入队myQueue.push(2);myQueue.push(3);cout<<"队头:"<<myQueue.front()<<endl;//获取队头元素cout<<"队尾:"<<myQueue.back()<<endl;//获取队尾元素cout<<"出队===="<<endl;myQueue.pop();//出队cout<<"队头:"<<myQueue.front()<<endl;cout<<"出队====="<<endl;myQueue.pop();cout<<"队头:"<<myQueue.front()<<endl;system("pause");return 0;
}
运行效果
以上程序运行的效果:
以上是用两个栈实现一个队列,重在实现思路的理解。
参考:https://blog.csdn.net/weixin_44781107/article/details/102506752