您的位置:首页 > 其它

如何用两个队列实现一个栈,并分析有关栈操作的运行时间。

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)。

代码实现如下:

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐