Hi guys I really need your help...
/>/>
the code is working fine but I couldn't figure out how to use copy constructor to copy an old stack into a new one (double the size when the array is full). any help would be appreciated
the code is working fine but I couldn't figure out how to use copy constructor to copy an old stack into a new one (double the size when the array is full). any help would be appreciated
template<class Type>
class Stack {
private:
int fullStack;
int topIndex;
Type* stackArray;
void copy(const Stack<Type>& other);
public:
Stack(int maxSize);//constructor
Stack(const Stack<Type>& other); //copy constructor
const Stack<Type>& operator=(const Stack<Type>&other); //assignment operator
~Stack();//destructor
void push(const Type& data);//add item in the stack
Type& pop(); //pop an item and return top element
int size(); //return the size of the stack
bool isEmpty(); //check if stack is empty
bool isFull(); //check if stack is full
};
//Stack implementation
template<class Type>
Stack<Type>::Stack(int maxSize)
{
if(stackArray == NULL)
{
cout<<"out of space!"<<endl;
}
else
{
fullStack = maxSize;
topIndex = -1;
stackArray = new Type[maxSize];
}
}
//copy constructor
template<class Type>
Stack<Type>::Stack(const Stack<Type>& other)
{
stackArray = NULL;
copy(other);
}
//overloading operator
template<class Type>
const Stack<Type>& Stack<Type>::operator=(const Stack<Type>&other)
{
if(this !=& other)
{
copy(other);
}
return *this;
}
//destructor
template<class Type>
Stack<Type>::~Stack()
{
delete [] stackArray; // delete dynamic array
}
//copy stack
template<class Type>
void Stack<Type>::copy(const Stack<Type>& other)
{
delete [] stackArray;
fullStack = other.fullStack;
topIndex = other.topIndex;
stackArray = new Type[fullStack];
//copy other stack into this stack
for( int i =0; i<fullStack; i++)
{
stackArray[i] = other.stackArray[i];
}
}
template<class Type>
void Stack<Type>::push(const Type& data)
{
//if stack is full print out a message
//else increment topIndex and store data in the stackArray
if(!isFull())
{
stackArray[++topIndex] = data;
}
else
{
cout<<"Stack is full, double stack size"<<endl;
Stack<Type> newStack(fullStack*2);
//need help on this part
//use copy constructor to copy old array into new array
//copy old stack into new stack
}
}
template<class Type>
Type& Stack<Type>::pop()
{
//check if it is not empty
//remove and return top element
if(isEmpty())
{
cout<<"Stack is empty"<<endl;
}
else
return stackArray[topIndex--];
}
template<class Type>
int Stack<Type>::size()
{
//return the size of the stack
return fullStack;
}
template<class Type>
bool Stack<Type>::isEmpty()
{
//return true if topIndex == -1, false otherwise
if( topIndex == -1)
{
return true;
}
else
return false;
}
template<class Type>
bool Stack<Type>::isFull()
{
//return true if topIndex+1 == full stack, false otherwise
if(topIndex+1 == fullStack)
{
return true;
}
else
return false;
}