1 #include <iostream> 2 #include <queue> 3 #include <climits> 4 #include <algorithm> 5 #include <memory.h> 6 #include <stdio.h> 7 #include <ostream> 8 #include <vector> 9 #include <list> 10 #include <cmath> 11 #include <string> 12 #include <stdexcept> 13 using namespace std; 14 15 class stack3parts 16 { 17 const int stackSize; 18 int top1; 19 int top2; 20 int top3; 21 int* data; 22 public: 23 stack3parts(int paramSize):stackSize(paramSize),top1(0),top2(paramSize),top3(2*paramSize) 24 { 25 data = new int[paramSize*3]; 26 } 27 28 void push(int stackNum,const int &elem) 29 { 30 switch(stackNum) 31 { 32 case 1: 33 if(top1 == stackSize) 34 throw std::out_of_range("stack1 is full!"); 35 data[top1++] = elem; 36 break; 37 case 2: 38 if(top2 == 2*stackSize) 39 throw std::out_of_range("stack2 is full!"); 40 data[top2++] = elem; 41 break; 42 case 3: 43 if(top3 == 3*stackSize) 44 throw std::out_of_range("stack3 is full!"); 45 data[top3++] = elem; 46 break; 47 } 48 } 49 50 int pop(int stackNum) 51 { 52 switch(stackNum) 53 { 54 case 1: 55 if(top1 == 0) 56 throw std::out_of_range("stack1 is empty!"); 57 top1--; 58 return data[top1]; 59 break; 60 case 2: 61 if(top2 == stackSize) 62 throw std::out_of_range("stack2 is empty!"); 63 top2--; 64 return data[top2]; 65 break; 66 case 3: 67 if(top3 == 2*stackSize) 68 throw std::out_of_range("stack3 is empty!"); 69 top3--; 70 return data[top3]; 71 break; 72 } 73 } 74 }; 75 int main() 76 { 77 stack3parts s(3); 78 s.push(1,2); 79 s.push(2,3); 80 s.push(3,4); 81 82 cout<<s.pop(1)<<endl; 83 cout<<s.pop(2)<<endl; 84 cout<<s.pop(3)<<endl; 85 86 s.pop(1); 87 return 0; 88 }
这个思路是对一个数组进行固定的大小分配,这样缺点是资源得不到充分利用