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

来源:互联网 发布:葛航 创业软件 知乎 编辑:程序博客网 时间:2024/06/13 08:41
  栈的操作主要有:入栈,出栈,返回栈顶元素,返回栈长度以及判断栈是否为空。

  若用两个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)。

代码实现如下:

复制代码
 1 #include <iostream> 2 #include <queue> 3 #include <cassert> 4 using namespace std; 5  6 template <class T> 7 class YL_Stack 8 { 9 public:10         YL_Stack():currentIndex(0)11         {12 13         }14         void push(const T &element); //入栈15         void pop();  //出栈16         T top();  //栈顶元素17         size_t size() const;  //栈的大小18         bool empty() const;   //判断栈是否为空19 20 21 private:22     int currentIndex;23     queue<T> q[2];24 };25 26 template <class T>27 void YL_Stack<T>::push(const T &element)28 {29     q[currentIndex].push(element);30 }31 32 template <class T>33 size_t YL_Stack<T>::size() const34 {35     return q[0].size()+q[1].size();36 }37 38 template <class T>39 bool YL_Stack<T>::empty() const40 {41     return (size()==0);42 }43 44 template <class T>45 void YL_Stack<T>::pop()46 {47     assert(!empty());48 49     int index=(currentIndex+1)%2;50     while(q[currentIndex].size()>1)51     {52         T temp=q[currentIndex].front();53         q[currentIndex].pop();54         q[index].push(temp);55     }56 57     q[currentIndex].pop();58     currentIndex=index;    59 }60 61 template <class T>62 T YL_Stack<T>::top()63 {64     assert(!empty());65 66     int index=(currentIndex+1)%2;67     T temp;68     while(q[currentIndex].size()>0)69     {70         temp=q[currentIndex].front();71         q[currentIndex].pop();72         q[index].push(temp);73     }74 75     currentIndex=index;76     return temp;77 }78 79 80 void main()81 {82     YL_Stack<int> myStack;83     myStack.push(1);84     myStack.push(2);85     myStack.push(3);86     myStack.push(4);87     myStack.push(5);88     cout<<"1栈的大小为:"<<myStack.size()<<endl;89     cout<<"1栈顶元素为:"<<myStack.top()<<endl;90     myStack.pop();91     myStack.pop();92     myStack.pop();93     cout<<"2栈的大小为:"<<myStack.size()<<endl;94     cout<<"2栈顶元素为:"<<myStack.top()<<endl;95         96 }
0 0
原创粉丝点击