用栈实现队列
用两个栈实现栈的思路如下:栈s1装新压入的元素,顺序是“倒过来的”(先进后出),要出栈的话就把s1存的元素倒入s2中,这时候s2中的元素的出栈顺序与队列的出队顺序相同。执行的步骤如下:1. 入队时,检测s1是否已满,未满则入栈。 2. 出队时,检测s2中是否还有元素,若不为空,直接出栈即可;若s2为空,将s1中的元素倒入s2后再弹出s2的栈顶。
具体代码如下:
1 #include <iostream> 2 using namespace std; 3 4 template <typename Type> class Stack{ 5 private: 6 Type *data; 7 int size,top_index; 8 public: 9 Stack(int input_size){ 10 size=input_size; 11 data=new Type[size]; 12 top_index=-1; 13 } 14 ~Stack(){ 15 delete[] data; 16 } 17 bool push(Type element){ 18 if(top_index+1>=size){ 19 return false; 20 } 21 top_index++; 22 data[top_index]=element; 23 return true; 24 } 25 Type top(){ 26 if(top_index<0){ 27 return NULL; 28 } 29 return data[top_index]; 30 } 31 bool pop(){ 32 if(top_index<0){ 33 return false; 34 } 35 top_index--; 36 return true; 37 } 38 bool empty(){ 39 return top_index<0; 40 } 41 int length(){ 42 return top_index+1; 43 } 44 }; 45
46 template <typename Type> class QueueByStack{ 47 private: 48 int size; 49 Stack<Type> *s1; 50 Stack<Type> *s2; 51 public: 52 QueueByStack(int input_size){ 53 size=input_size; 54 s1=new Stack<Type>(size); 55 s2=new Stack<Type>(size); 56 } 57 ~QueueByStack(){ 58 s1->~Stack(); 59 s2->~Stack(); 60 } 61 bool push(Type element){ 62 return s1->push(element); 63 } 64 bool empty(){ 65 return s1->empty()&&s2->empty(); 66 } 67 //make sure the queue is not empty first 68 Type front(){ 69 if(!s2->empty()){ 70 return s2->top(); 71 } 72 else{ 73 //把s1中的元素全部倒入s2中 74 while(!s1->empty()){ 75 Type temp=s1->top(); 76 s1->pop(); 77 s2->push(temp); 78 } 79 return s2->top(); 80 } 81 } 82 //make sure the queue is not empty first 83 void pop(){ 84 if(!s2->empty()){ 85 s2->pop(); 86 } 87 else{ 88 //把s1中的元素全部倒入s2中 89 while(!s1->empty()){ 90 Type temp=s1->top(); 91 s1->pop(); 92 s2->push(temp); 93 } 94 s2->pop(); 95 } 96 } 97 }; 98 //for testing 99 int main(){ 100 QueueByStack<int> queue(10); 101 for(int i=1;i<=10;i++){ 102 queue.push(i); 103 } 104 for(int i=1;i<=5;i++){ 105 if(!queue.empty()) queue.pop(); 106 } 107 for(int i=1;i<=5;i++){ 108 if(!queue.empty()) cout<<queue.front()<<" "; 109 if(!queue.empty()) queue.pop(); 110 } 111 cout<<endl; 112 //the output is:6 7 8 9 10 113 }