I have a class stack which is defined like this:
#ifndef STACK_H
#define STACK_H
#include "MyException.h"
#include <iostream>
using namespace std;
template<class T>
class Stack;
template<class T>
ostream& operator<<(ostream&,Stack<T>&);
template<class T>
class Stack
{
public:
friend ostream& operator<< <T>(ostream&,Stack<T>&);
/*The constructor for the Stack class*/
Stack();
/*The copy constructor*/
Stack(const Stack<T>& other);
Stack<T>& operator=(const Stack<T>& other);
/*The destructor for the stack class*/
~Stack();
void push(const T& el);
T pop();
bool isEmpty();
private:
/*The node class.*/
class Node
{
public:
Node(const T& data, Node* n = 0)
{
element = data;
next = n;
}
T element;
Node* next;
};
/*The top of the stack*/
Node* top;
};
#include "Stack.C"
#endif
And I have to perform a deep copy in my copy constructor. But what I did was create an temporary array and copy all the elements in the object received by the parameter into the array and then node into the array then push all of them to into the node defined in the Stack class. This is how I did it:
template<class T>
Stack<T>::Stack(const Stack<T>& other)
{
top = NULL;
if(other.top == NULL)
{
this->top=NULL;
}
else
{
Node* count;
count= other.top;
int num=1;
while(count->next != NULL)
{
num++;
count = count->next;
}
cout<<"test"<<endl;
T arr[num];
arr[0] = other.top->element;
Node* count2;
count2= other.top;
for(int i = 1 ; i<num; i++)
{
arr[i] = count2->next->element;
count2 = count2->next;
}
T temp;
for(int i =0, j=num-1; i<num/2 ; i++, j--)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for(int i =0; i<num; i++)
{
push(arr[i]);
cout<<arr[i]<<endl;
}
}
}
You can assume that my push(const T& el) and pop() works fine. Can anyone help me perform a deep copy?
while
loop should be enough to initialize the nodes on the object being constructed.Stack
class. When you allocate a large local arrayT arr[num]
there is a possibility to have call stack overflow.for (Node* p = other.top; p; p = p->next) push(*p);