Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Did I do this right? #include \"StackArray.h\" template <typename DataType> Stac

ID: 3723175 • Letter: D

Question

Did I do this right?

#include "StackArray.h"

template <typename DataType>

StackArray<DataType>::StackArray(int maxNumber)

{

top = -1;

maxSize = maxNumber;

dataItems = new DataType[maxSize];

}

template <typename DataType>

StackArray<DataType>::StackArray(const StackArray& other)

{

clear();

if (other.top > -1)

{

dataItems = new DataType[other.maxSize];

mazSize = other.maxSize;

top = other.top;

for (int i = 0; i <= top; i++)

{

dataItems[i] = other.dataItems[i];

}

}

}

template <typename DataType>

StackArray<DataType>& StackArray<DataType>::operator=(const StackArray& other)

{

if (this != &other)

{

clear();

if (other.top != -1)

{

dataItems = new DataType[other.maxSize];

mazSize = other.maxSize;

top = other.top;

for (int i = 0; i <= top; i++)

{

dataItems[i] = other.dataItems[i];

}

}

}

return *this;

}

template <typename DataType>

StackArray<DataType>::~StackArray()

{

clear();

}

template <typename DataType>

void StackArray<DataType>::push(const DataType& newDataItem) throw (logic_error)

{

if (isFull())

throw logic_error("The stack is full: No room to add an item. ");

dataItems[++top] = newDataItem;

}

template <typename DataType>

DataType StackArray<DataType>::pop() throw (logic_error)

{

if (isEmpty())

throw logic_error("The stack is empty: No item to remove. ");

return dataItems[top--];

}

template <typename DataType>

void StackArray<DataType>::clear()

{

if (dataItems != NULL)

delete[] dataItems;

dataItems = NULL;

}

template <typename DataType>

bool StackArray<DataType>::isEmpty() const

{

return top < 0;

}

template <typename DataType>

bool StackArray<DataType>::isFull() const

{

return top == (maxSize - 1);

}

template <typename DataType>

void StackArray<DataType>::showStructure() const

// Array implementation. Outputs the data items in a stack. If the

// stack is empty, outputs "Empty stack". This operation is intended

// for testing and debugging purposes only.

{

if( isEmpty() ) {

cout << "Empty stack." << endl;

}

else {

int j;

cout << "Top = " << top << endl;

for ( j = 0 ; j < maxSize ; j++ )

cout << j << " ";

cout << endl;

for ( j = 0 ; j <= top ; j++ )

{

if( j == top )

{

cout << '[' << dataItems[j] << ']'<< " "; // Identify top

}

else

{

cout << dataItems[j] << " ";

}

}

cout << endl;

}

cout << endl;

}

Explanation / Answer

Looks correct to me,

top initialiased to -1.
empty is checked based on top <0
etc

Thanks, let me know if you have any doubts, Please comment

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote