Describe how you could use a single array to implement three stacks.
1 typedef struct Node{ 2 int val,preIdex; 3 Node(int val = INT_MIN,int preIndex=-2):val(val),preIndex(preIndex){} 4 }; 5 6 class Stack3{ 8 public: 9 Stack3(int totalSize = 900){ 10 buf = new Node[totalSize]; 11 ptop[0] = -1; 12 ptop[1] = -1; 13 ptop[2] = -1; 14 this->totalSize = totalSize; 15 } 16 17 ~Stack3(){ 18 delete[] buf; 19 } 20 21 void Push(int stackNum,int val){ 22 bur[cur].val = val; 23 bur[cur].preIndex = ptop[stackNum]; 24 ptop[stackNum] = cur++; 25 26 //沿着数组一次向后查找,直到找到第一个空的 27 while(cur<totalSize){ 28 if(buf[i].preIndex == -2) 29 break; 30 } 31 } 32 33 void Pop(int stackNum){ 34 35 //每次执行pop操作,检查该元素对应索引是否小于cur,如果是, 将cur更新到该元素索引;否则cur不变 36 if(ptop[stackNum]<cur) 37 cur = ptop[stackNum]; 38 //清楚数据 39 buf[ptop[stackNum]].val = INT_MIN; 40 ptop[stackNum] = buf[ptop[stackNum]].preIndex; 41 buf[ptop[stackNum]].preIndex = -2; 42 43 } 44 45 int top(int stackNum){ 46 return buf[ptop[stackNum]].val; 47 } 48 49 bool empty(int stackNum){ 50 return ptop[stackNum]== -1; 51 } 52 53 private: 54 Node *buf; 55 int ptop[3]; 56 int totalSize; 57 int cur; 58 };