如何用两个队列实现一个栈,并分析有关栈操作的运行时间。
2012-08-16 17:16
706 查看
栈的操作主要有:入栈,出栈,返回栈顶元素,返回栈长度以及判断栈是否为空。
若用两个queue实现(可以定义成queue的数组queue q[2]),可以增加一个currentIndex来指向当前选中的queue。入栈操作可以直接把元素加到queue里,即 queue[currentIndex].push(element),时间复杂度为O(1),出栈操作要复杂一些,还是因为栈和队列元素的出入顺序不 同,处理方法是将size()-1个元素从q[currentIndex]转移到空闲队列q[(currentIndex + 1)%2]中,q[currentIndex]最后一个剩下的元素恰对应栈顶元素,之后更新一下currentIndex即可,时间复杂度为O(N)。
代码实现如下:
若用两个queue实现(可以定义成queue的数组queue q[2]),可以增加一个currentIndex来指向当前选中的queue。入栈操作可以直接把元素加到queue里,即 queue[currentIndex].push(element),时间复杂度为O(1),出栈操作要复杂一些,还是因为栈和队列元素的出入顺序不 同,处理方法是将size()-1个元素从q[currentIndex]转移到空闲队列q[(currentIndex + 1)%2]中,q[currentIndex]最后一个剩下的元素恰对应栈顶元素,之后更新一下currentIndex即可,时间复杂度为O(N)。
代码实现如下:
#include <iostream> #include <queue> #include <cassert> using namespace std; template <class T> class YL_Stack { public: YL_Stack():currentIndex(0) { } void push(const T &element); //入栈 void pop(); //出栈 T top(); //栈顶元素 size_t size() const; //栈的大小 bool empty() const; //判断栈是否为空 private: int currentIndex; queue<T> q[2]; }; template <class T> void YL_Stack<T>::push(const T &element) { q[currentIndex].push(element); } template <class T> size_t YL_Stack<T>::size() const { return q[0].size()+q[1].size(); } template <class T> bool YL_Stack<T>::empty() const { return (size()==0); } template <class T> void YL_Stack<T>::pop() { assert(!empty()); int index=(currentIndex+1)%2; while(q[currentIndex].size()>1) { T temp=q[currentIndex].front(); q[currentIndex].pop(); q[index].push(temp); } q[currentIndex].pop(); currentIndex=index; } template <class T> T YL_Stack<T>::top() { assert(!empty()); int index=(currentIndex+1)%2; T temp; while(q[currentIndex].size()>0) { temp=q[currentIndex].front(); q[currentIndex].pop(); q[index].push(temp); } currentIndex=index; return temp; } void main() { YL_Stack<int> myStack; myStack.push(1); myStack.push(2); myStack.push(3); myStack.push(4); myStack.push(5); cout<<"1栈的大小为:"<<myStack.size()<<endl; cout<<"1栈顶元素为:"<<myStack.top()<<endl; myStack.pop(); myStack.pop(); myStack.pop(); cout<<"2栈的大小为:"<<myStack.size()<<endl; cout<<"2栈顶元素为:"<<myStack.top()<<endl; }
相关文章推荐
- 如何用两个队列实现一个栈,并分析有关栈操作的运行时间。
- 如何用两个栈来实现一个队列,并分析有关队列操作的运行时间。
- 10.1-2 说明如何用一个数组A[1..n]来实现两个栈,使得两个栈中的元素总数不到n时,两者都不会发生上溢,注意PUSH和POP操作的时间应为O(1)。
- (p131)用两个栈实现一个队列,运行时间为o(n)
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 算法分析:两个栈实现一个队列
- 使用两个Stack类(JDK容器类库中的Stack类)实现一个队列类MyQueue,提供队列的入队列和出队列操作:enQueue和deQueue
- 用两个栈来实现一个队列完成队列的Push和Pop操作 队列中的元素为int类型。
- javascript操作两个选择列表(有两个列表,如何实现在一个列表通过双击和多选列表中内容添加到另一个列表. )
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- Rhyme/剑指Offer Java05 拓展 用两个队列实现一个栈的push和pop操作
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 用两个栈实现队列 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
- 数据结构:栈和列之如何用两个队列实现一个栈?两个栈实现一个队列?
- 在一个Android项目里面有两个可运行文件,如何实现调用方式
- 两个队列实现一个栈,并实现入栈、出栈、取栈顶等相关操作