I'm trying to perform a deep copy for my Queue (FIFO) using nodes and I'm getting an error and Don't know what's causing it. All the methods work fine when I don't copy anything but as soon as I try to copy I get a "MyQueue.exe" stopped working. This happens when I don't even use the methods. It also happens even if I comment out the whole do-while loop. Anyone know what's causing this?
MyQueue::MyQueue (void)
{
head = NULL;
queueSize = 0;
}
MyQueue::MyQueue (const MyQueue & myq)
{
copyQueue (myq);
}
MyQueue & MyQueue::operator = (const MyQueue & myq)
{
copyQueue (myq);
return *this;
}
void MyQueue::copyQueue (const MyQueue & myq)
{
head = NULL;
queueSize = 0;
Node* temp = myq.head->next;
do
{
enqueue(myq.head->data);
temp = temp->next;
}
while ( temp->next != NULL );
}
MyQueue::~MyQueue (void)
{
}
void MyQueue::enqueue (const int n)
{
Node* temp = tail;
tail = new Node (n);
queueSize++;
if ( empty() )
{
head = tail;
}
else
{
temp->next = tail;
}
}
int MyQueue::dequeue (void)
{
if ( !empty() )
{
int result = head->data;
Node* temporary = head;
head = (temporary->data, temporary->next);
queueSize--;
return result;
}
else
{
std::cout << "No Items to remove" << std::endl;
return NULL;
}
}
int MyQueue::peek (void)
{
return head->data;
}
bool MyQueue::empty (void)
{
if ( head == NULL || queueSize == 0)
{
return true;
}
return false;
}
This is how my node is copied
Node & Node::operator = (const Node* & nd)
{
data = nd->data;
next = nd->next;
}
MyQueue q1;
MyQueue q2 = q1; // Crash.
This will crash, because the head
is NULL, and you dereference it in the copyQueue()
method.
Node* temp = myq.head->next;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.