Stack Code

 avatar
Sameh
c_cpp
7 months ago
1.9 kB
1
Indexable
Never
#include <iostream>

using namespace std;

//constructor , push , pop , isFull , isEmpty , doubleSize , getStackMaxSize , getTopData , getTopCounter , displayData , destructor

class arrayStack
{
    int * stackArray , sizeOfStack , top;
public:
    arrayStack(int sizeOfArray = 1)
    {
        sizeOfStack = sizeOfArray;
        stackArray = new int [sizeOfStack];
        top = 0;
    }
    bool isFull()
    {
        return sizeOfStack == top;
    }
    void doubleSize()
    {
        int * tempArray = new int [sizeOfStack * 2];
        for(int i = 0 ; i < sizeOfStack ; i++)
        {
            tempArray[i] = stackArray[i];
        }
        sizeOfStack *= 2;
        delete[] stackArray;
        stackArray = tempArray;
    }
    void push(int data)
    {
        if(isFull())
            doubleSize();
        stackArray[top] = data;
        top++;
    }
    bool isEmpty()
    {
        return top == 0;
    }
    int pop()
    {
        if(isEmpty())
        {
            cout << "Stack is empty\n";
            return -1;
        }
        top--;
        return stackArray[top];
    }
    int getStackMaxSize()
    {
        return sizeOfStack;
    }
    int getTopData()
    {
        return stackArray[top - 1];
    }
    int getTopCounter()
    {
        return top;
    }
    void displayData()
    {
        for(int i = top - 1 ; i>= 0; i--)
            cout << stackArray[i] << "\t";
    }
    ~arrayStack()
    {
        cout << "Stack is deleted\n";
        delete[] stackArray;
    }
};

int main()
{
    arrayStack stack1(5);
    for(int i = 0 ; i < 10 ; i++)
        stack1.push(i);
    cout << stack1.getStackMaxSize() << "\n";
    stack1.displayData();
    cout << "\n" << stack1.pop() << "\t" << stack1.pop() << "\n";
    stack1.displayData();
    cout << "\n";
    return 0;
}
Leave a Comment