Array Stack Implementation

#include <iostream> using namespace std; class ArrayStack { private: int top; int capacity; int *storage; public: ArrayStack(int capacity) { storage = new int[capacity]; this->capacity = capacity; top = -1; } ~ArrayStack() { delete[] storage; } void push(int value) { if (top == capacity - 1) throw string("Stack is overflow"); top++; storage[top] = value; } void pop(int &dataOut) { if (top == -1) throw string("Stack is empty"); dataOut = storage[top]; top--; } int getTop() { if (top == -1) throw string("Stack is empty"); return storage[top]; } bool isEmpty() { return (top == -1); } bool isFull() { return (top == capacity-1); } int getSize() { return top + 1; } void print2Console() { if (top > -1) { for (int i = top; i >= 0; i--) { cout << storage[i] << " "; } cout << endl; } } }; int main() { cout << "Array Stack" << endl; ArrayStack *myStack = new ArrayStack(10); int val; myStack->push(7); myStack->push(9); myStack->push(10); myStack->push(8); myStack->print2Console(); myStack->pop(val); myStack->print2Console(); delete myStack; return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.