如何用两个队列实现一个栈,并分析有关栈操作的运行时间。
来源:互联网 发布:葛航 创业软件 知乎 编辑:程序博客网 时间: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
- 如何用两个队列实现一个栈,并分析有关栈操作的运行时间。
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈模拟队列操作
- 如何用两个栈视线一个队列
- 如何用两个栈形成一个队列
- 如何用两个栈实现一个队列,以及用两个队列实现一个栈
- Java:如何用两个队列实现栈
- 如何用两个栈来实现队列的方法
- 如何用两个栈实现队列的功能
- 如何用两个栈来实现队列的方法
- 如何用一个栈实现队列?
- 数据结构:栈和列之如何用两个队列实现一个栈?两个栈实现一个队列?
- 如何用两个栈实现一个队列(思路)(欢迎提意见)
- 如何用栈实现队列的功能
- 两个栈实现一个队列,并实现队列入队、出队、取队头、取队尾相关操作
- 使用Jmai发送邮件
- Struts 2 Hello World Annotation Example
- LINK:fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- Java EE文件上传
- 关于JSP九大内置对象、四大作用域和session的生命周期
- 如何用两个队列实现一个栈,并分析有关栈操作的运行时间。
- LeetCode|Majority Element-java
- $ git push origin test:master // 提交本地test分支 作为 远程的master分支
- css里面常用一些通用样式写法
- 对于IT人非常有价值的博客,常来看看。
- iOS - 强制旋转屏幕之代码实现
- jsckson常用注解
- requestFocus() 无效的原因
- 在Mac下配置Caffe笔记