Stack using Array
itsLu
c_cpp
a year ago
1.8 kB
11
Indexable
#include <iostream> using namespace std; //constructor , push , pop , isFull , isEmpty , doubleSize , getStackMaxSize , getTopData , getTopCounter , displayData , destructor class stackArray { int stackSize, top, *arr; public: stackArray(int s = 1) { stackSize = s; arr = new int [stackSize]; top = 0; } bool isFull () { return top == stackSize; } void doubleSize() { int *tempArray = new int [stackSize * 2]; for (int k = 0 ; k < stackSize ; k++) tempArray[k] = arr[k]; stackSize *= 2; delete [] arr; arr = tempArray; } void push(int item) { if (isFull()) doubleSize(); arr[top] = item; top++; } bool isEmpty () { return top == 0; } int pop() { if (isEmpty()) { cout << "Stack is empty!\n"; return -1; } top--; return arr[top]; } int getMaxSize() { return stackSize; } int getTopData() { return arr[top - 1]; } int getTopCounter() { return top; } void displayData() { for (int k = top - 1 ; k >= 0 ; k--) cout << arr[k] << "\t"; } ~stackArray() { delete [] arr; cout << "Stack is deleted!\n"; } }; int main() { stackArray stack1(5); for(int i = 0 ; i < 10 ; i++) stack1.push(i); cout << stack1.getMaxSize() << "\n"; stack1.displayData(); cout << "\n" << stack1.pop() << "\t" << stack1.pop() << "\n"; stack1.displayData(); cout << "\n"; return 0; }
Editor is loading...
Leave a Comment