// NET2006-5-Stakaray-Improved-RangeChecking.cpp // an improved stack class #include using namespace std; //////////////////////////////////////////////////////////////// class Stack { private: static const int MAX = 10; // better approach: static means one and // only one instance for all stack objects int nTop; // Number of nTop of stack int anStack[MAX]; // Stack: array of integers public: stack() // Constructor { nTop = -1; // -1 means that the stack is empty } bool IsEmpty() { return (nTop <= -1); } void IsFull() { return (nTop >= MAX-1); } void Push(int nVarIn) // Put number on stack { if (IsFull()) { // Watch for array overrun cout << "Stack Full\n"; return false; } else { anStack[++nTop] = nVarIn; return true; } } int Pop() // Take number off stack { if (IsEmpty()) // Watch for array underrun cout << "Empty Stack\n"; else return anStack[nTop--]; } } //////////////////////////////////////////////////////////////// void main() { Stack s1; s1.Push(11); s1.Push(12); Stack s2; s2.Push(21); s2.Push(22); cout << "s1.1: " << s1.Pop() << endl; //12 cout << "s1.2: " << s1.Pop() << endl; //11 s2.Push(23); s2.Push(24); cout << "s2.1: " << s2.Pop() << endl; //24 cout << "s2.2: " << s2.Pop() << endl; //23 s1.Push(13); s1.Push(14); s1.Push(15); s1.Push(16); cout << "s1.3: " << s1.Pop() << endl; //16 cout << "s1.4: " << s1.Pop() << endl; //15 cout << "s1.5: " << s1.Pop() << endl; //14 cout << "s1.6: " << s1.Pop() << endl; //13 if (s1.IsEmpty()) cout << "Stack 1 is empty"; else cout << "Stack 2 has remaining items."; if (s2.IsEmpty()) cout << "Stack 2 is empty"; else cout << "Stack 2 has remaining items."; }