实现if_数组实现固定栈和队列+栈与队列相互实现
生活随笔
收集整理的這篇文章主要介紹了
实现if_数组实现固定栈和队列+栈与队列相互实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、數組實現固定棧和隊列
- 1.數組實現固定棧
- 2.數組實現固定隊列
- 二、棧與隊列相互實現
- 1.兩個隊列實現棧
- 2.兩個棧實現隊列
一、數組實現固定棧和隊列
1.數組實現固定棧
代碼如下:
class ArrayStack { private:int *arr;int index; public:ArrayStack(int initSize){if(initSize>=0){arr=new int[initSize];}index=0;}void push(int obj){if(index!=arr.size()){arr[index++]=obj;}}int pop(){if(arr.size()!=0){return arr[--index];}return 0;}int peek(){if(index!=0)return arr[index-1];return 0;} };2.數組實現固定隊列
代碼如下:
class ArrayQueue {private: int* arr;int size;int first;int last;public: ArrayQueue(int initSize) {if (initSize < 0) {cout<<"error"<<endl;}arr = new int[initSize];size = 0;first = 0;last = 0;}int peek() {if (size == 0) {return null;}return arr[first];}void push(int obj) {if (size == arr.size()) {cout<<"error"<<endl;}size++;arr[last] = obj;last = last == arr.size() - 1 ? 0 : last + 1;}int poll() {if (size == 0) {cout<<"error"<<endl;}size--;int tmp = first;first = first == arr.size() - 1 ? 0 : first + 1;return arr[tmp];}};二、棧與隊列相互實現
1.兩個隊列實現棧
代碼如下:
class TwoQueueStack { private:queue<int> data;queue<int> help; public:TwoQueueStack(){data=new list<int>();help=new list<int>();}void my_push(int obj){data.push(obj);}int my_pop(){while(data.size()>1){help.push(data.front());data.pop();}int res=data.front();swap();return res;}int peek(){while(data.size()>1){help.push(data.front());data.pop();}int res=data.front();help.push(res);swap();return res;} } ;2.兩個棧實現隊列
代碼如下:
class TwoStacksQueue {private: stack<int> stackPush;stack<int> stackPop;public:TwoStacksQueue() {stackPush = new stack<int>();stackPop = new stack<int>();}void push(int pushInt) {stackPush.push(pushInt);}void pop() {if (stackPop.empty() && stackPush.empty()) {cout<<"Queue is empty!"<<endl;} else if (stackPop.empty()) {while (!stackPush.empty()) {stackPop.push(stackPush.top());stckPush.pop();}}stackPop.pop();return ;}int top() {if (stackPop.empty() && stackPush.empty()) {cout<<"Queue is empty!"<<endl;} else if (stackPop.empty()) {while (!stackPush.empty()) {stackPop.push(stackPush.top());stckPush.pop();}}return stackPop.top();}}; 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的实现if_数组实现固定栈和队列+栈与队列相互实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云教版认识计算机说课,【教学设计】第1册
- 下一篇: 模拟 http connecttimeo