数据结构复习之用两个栈模拟队列操作
2017-04-02 18:12
411 查看
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #define MAXSIZE 100 using namespace std; struct Stack{ int s[MAXSIZE]; int top=0; bool stackOverFlow(){ if(top >= MAXSIZE) return true; return false; } bool push(int x){ if(stackOverFlow()) return false; s[top++] = x; } bool isEmpty(){ return top==0 ? true : false; } bool pop(int &x){ if(isEmpty()) return false; x = s[--top]; return true; } int size(){ return top; } }; struct Queue{//这种实现方式也是最容易想到的 Stack s1, s2;//s1用于队列的push和pop, s2用于是的缓冲(将s1中的数据进行反转,就成了队列的顺序) bool push(int x){ if(s1.stackOverFlow()) return false; int e; while(!s1.isEmpty()){ s1.pop(e); s2.push(e); } s1.push(x); while(!s2.isEmpty()){ s2.pop(e); s1.push(e); } return true; } bool pop(int &x){ if(s1.isEmpty()) return false; s1.pop(x); return true; } bool isEmpty(){ return s1.size() == 0 ? true : false; } int size(){ return s1.size(); } }; struct Queue_x{//这种方式的空间利用率更大一些 Stack s1, s2;//s1用于队列的push, s2用于队列的pop bool push(int x){ if(!s1.stackOverFlow()) { s1.push(x); return true; } if(s1.stackOverFlow() && !s2.isEmpty()) return false; int e; while(!s1.isEmpty()){ s1.pop(e); s2.push(e); } s1.push(x); return true; } bool pop(int &x){ if(!s2.isEmpty()){ s2.pop(x); return true; } if(s1.isEmpty()) return false; int e; while(!s1.isEmpty()){ s1.pop(e); s2.push(e); } s2.pop(x); return true; } bool isEmpty(){ return s1.size() == 0 && s2.size() == 0; } int size(){ return s1.size() + s2.size(); } }; int main(){ Queue q; for(int i=0; i<10; ++i) q.push(i); int x; for(int i=0; i<10; ++i){ q.pop(x); cout<<x<<endl; q.push(100); } cout<<"队列的当前大小:"<<q.size()<<endl; while(!q.isEmpty()){ q.pop(x); cout<<x<<endl; } cout<<"******************************************************"<<endl; Queue_x qx; for(int i=0; i<10; ++i) qx.push(i); for(int i=0; i<10; ++i){ qx.pop(x); cout<<x<<endl; qx.push(100); } cout<<"队列的当前大小:"<<qx.size()<<endl; while(!qx.isEmpty()){ qx.pop(x); cout<<x<<endl; } return 0; }
相关文章推荐
- 数据结构复习之用两个栈模拟队列操作
- 如何使用两个栈模拟队列操作
- 剑指offer之两个栈模拟队列操作
- 【数据结构与算法C】利用两个栈S1S2模拟一个队列,用栈的基本操作实线EnQueue,DeQueue,QueueEmpty
- 使用两个栈模拟队列的操作
- 如何用两个栈模拟队列操作
- 数据结构 用两个栈来模拟一个队列
- 【学习点滴-数据结构-栈&队列】 用两个栈模拟一个队列
- 剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作
- 统计工龄 模拟EXCEL排序 银行排队问题之单队列多窗口问题 银行业务队列简单模拟 堆栈操作合法性 两个有序序列的中位数
- 002使用两个栈模拟队列的基本操作
- 数据结构 编写一个类,用两个栈实现队列,支持队列的基本操作(add 、poll、peek)
- 用两个栈模拟队列操作
- 两个队列模拟栈的操作(stl实现)
- 【学习点滴-数据结构-栈&队列】 用两个队列模拟一个栈
- 面试题9:用两个栈模拟一个队列的操作
- 数据结构队列的各种操作
- 使用两个栈模拟队列
- 数据结构学习笔记 --- 队列的应用举例(离散事件模拟)
- 数据结构(Java 队列模拟)本代码重在学习数据结构思路,代码完整性欠缺,请见谅