题目分析
栈:后进先出
队列:先进先出
要使用两个栈实现队列(先进先出),主要思路是
1.插入一个元素:直接将元素插入stack1即可。
2.删除一个元素:当stack2不为空时 ,直接弹出栈顶元素,当stack2为空时,将stack1元素逐个弹出并压入stack2,然后再弹出栈顶元素。
思路总结:
实现队列的pop方法弹出队头元素:stack是一个口进出,也不支持随机存取,所以你无法直接从栈底拿到第一个元素。要想拿到第一个元素,需要将左边栈容器中的所有元素拷贝到右边栈容器中。由于stack先进后出的数据结构,这样左边容器的第一个元素会作为最后一个元素存储到右边栈容器中,这样不就拿到左边栈容器中的第一个元素了吗 ?
实现队列的back方法获取队列的队尾元素:逻辑和思路1一样,唯一不同的是pop和top

代码如下:
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class MyQueue
{
public:
bool empty()const
{
return head.empty()&&tail.empty();
}
void push(T t)
{
head.push(t);
}
//删除对头元素
//因为queue是一种先进先出,而stack是先进后出,所以需要把head里的数据拷贝到tail中然后再从tail中pop头元素
void pop()
{
if(this->empty())
{
//throw exception("队列为NULL");
}
while(!head.empty())
{
tail.push(head.top());
head.pop();
}
//删除头元素
tail.pop();
//再将队尾栈容器元素拷贝到队头栈容器中
while(!tail.empty())
{
head.push(tail.top());
tail.pop();
}
}
T& back()
{
if(this->empty())
{
// throw exception("head is NULL");
}
return head.top();
}
//返回第一个元素
T& front()
{
if(this->empty())
{
//throw exception("队列为NULL");
}
while(!head.empty())
{
tail.push(head.top());
head.pop();
}
int tmp = tail.top();
//再将队尾栈容器元素拷贝到队头栈容器中
while(!tail.empty())
{
head.push(tail.top());
tail.pop();
}
return tmp;
}
private:
stack<int> head;
stack<int> tail;
};
int main()
{
MyQueue<int> q;
for(int i=1;i<5;i++)
{
q.push(i);
}
cout<<"front:"<<q.front()<<endl;
cout<<"back:"<<q.back()<<endl;
return 0;
}
本文介绍如何利用两个栈实现一个队列,包括插入元素(直接入栈1)和删除元素(栈2非空则直接出栈,否则将栈1元素移到栈2后出栈)。通过这种方式,可以利用栈的后进先出特性来模拟队列的先进先出行为。
1575

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



