1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| class TripleInOne { public: TripleInOne(int stackSize) : stacks(new int[stackSize * 3 + 3]), top1(0), top2(stackSize + 1), top3((stackSize << 1) + 2), stackSize(stackSize) { } void push(int stackNum, int value) { switch(stackNum) { case 0 : if(top1 == stackSize) return; stacks[++top1] = value; break; case 1: if(top2 == (stackSize << 1) + 1) return; stacks[++top2] = value; break; case 2: if(top3 == stackSize * 3 + 2) return; stacks[++top3] = value; break; } } int pop(int stackNum) { if(isEmpty(stackNum)) return -1; switch(stackNum) { case 0 : return stacks[top1--]; case 1: return stacks[top2--]; case 2: return stacks[top3--]; } return -1; } int peek(int stackNum) { if(isEmpty(stackNum)) return -1; switch(stackNum) { case 0 : return stacks[top1]; case 1: return stacks[top2]; case 2: return stacks[top3]; } return -1; } bool isEmpty(int stackNum) { switch(stackNum) { case 0 : return top1 == 0; case 1: return top2 == stackSize + 1; case 2: return top3 == (stackSize << 1) + 2; } return false; } private: int* stacks; int stackSize; int top1; int top2; int top3; };
|