
文章目录
- 一、数组实现固定栈和队列
- 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();}};