//------------------------------------------------------------ // Example program to demonstrate stacks with dynamic // array creation // // L.Aamodt // 5/06/14 //------------------------------------------------------------ #include #include using namespace std; const int DEFAULT_STACK_SIZE = 10; class mystack // Class definition { public: mystack(); // Default constructor mystack(int size); bool Empty(); void push(int value); int top(); void pop(); void display(); private: // Data int stkTop, stkSize; //int stkArray[DEFAULT_STACK_SIZE]; int *stkArray; }; mystack::mystack() // Default constructor { stkTop = -1; stkArray = new int [DEFAULT_STACK_SIZE]; // array size hard coded stkSize = DEFAULT_STACK_SIZE; } mystack::mystack(int size) // Constructor with size parameter { stkTop = -1; stkArray = new int [size]; // array size is a parameter stkSize = size; } void mystack::push(int value) // Place another item on stack { if (stkTop > stkSize - 2) { cerr << "stack overflow"; exit(1); } else { stkTop = stkTop + 1; stkArray[stkTop]=value; } return; } void mystack::pop() // Remove top item from stack { if (stkTop == -1) { cerr << "stack is empty. nothing to pop"; exit(2); } else { stkTop = stkTop -1; } return; } int mystack::top() // Get a copy of the top item on stack { int value; if (stkTop <= -1) { cerr << "stack empty" << endl; return 0; exit(3); } else { value = stkArray[stkTop]; return value; } } void mystack::display() // Print stack contents { if (stkTop == -1) cout << "Stack is Empty" << endl; else { cout << "Stack values are:" << endl; for (int i=0; i<=stkTop; i++ ) { cout << stkArray[i] << endl; } } return; } int main() // Test the stack functions { mystack stack1; int i; for (i=0; i<10; i++) { stack1.push(i*10); } stack1.display(); return 0; }