【5】用两个栈实现队列
2016-06-22 11:07
766 查看
【5】用两个栈实现队列
时间限制:1秒空间限制:32768K
本题知识点: 栈 队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题目链接:牛客网题目
vs2010编译通过
完整代码:#include<iostream> #include<stack> using namespace std; class Solution { public: void push(int node) { while(!stack2.empty()) { stack1.push( stack2.top() ); stack2.pop(); } stack1.push(node); } int pop() { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } int temp=stack2.top(); stack2.pop(); return temp; } bool empty() //如何判断栈空和栈满。 { if(stack1.empty() && stack2.empty()) return true; else return false; } private: stack<int> stack1; stack<int> stack2; }; int main() { Solution qs; qs.push(1); qs.push(2); qs.push(3); cout<<qs.pop()<<endl; qs.push(4); while(!qs.empty()) { cout<<qs.pop()<<endl; } //cout<<qs.pop(); //cout<<qs.pop(); }
方法一:
算法部分:不停倒换,复杂度较高class Solution { public: void push(int node) { while(!stack2.empty()) { stack1.push( stack2.top() ); stack2.pop(); } stack1.push(node); } int pop() { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } int temp=stack2.top(); stack2.pop(); return temp; } private: stack<int> stack1; stack<int> stack2; };
方法二:
算法部分,有点像流的缓冲区的感觉,避免不停倒换,时间效率更高class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack2.empty()) //如果栈2为空,将栈1中的元素流过来 { while(!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } int result=stack2.top(); stack2.pop(); return result; } private: stack<int> stack1; //只负责入栈 stack<int> stack2; //只负责出 };
测试通过图片
相关文章推荐
- C++基于栈实现铁轨问题
- C语言栈的表示与实现实例详解
- C语言实现颠倒栈的方法
- 算法系列15天速成 第十天 栈
- 一看就懂:图解C#中的值类型、引用类型、栈、堆、ref、out
- Array栈方法和队列方法的特点说明
- java数据结构之java实现栈
- 浅析栈区和堆区内存分配的区别
- 用Java代码实现栈数据结构的基本方法归纳
- 用PHP解决的一个栈的面试题
- 浅谈C#中堆和栈的区别(附上图解)
- JavaScript数据结构与算法之栈详解
- C语言之栈和堆(Stack && Heap)的优缺点及其使用区别
- Python实现栈的方法
- JavaScript数组的栈方法与队列方法详解
- JavaScript数据结构与算法之栈与队列
- JavaScipt中栈的实现方法
- Java中堆和栈的区别详解
- 详解Java的堆内存与栈内存的存储机制
- java中堆和栈的区别分析