I wrote an implementation for a simple queue in C++ (for practice, since there's an stl queue). I've been trying to focus on memory management and the rule of three. Any suggestions/improvements?
(Personally, I feel like there has to be a better way to overload the copy assignment operator).
#ifndef QUEUE_H
#define QUEUE_H
#include "assert.h"
#define NULL 0
template <typename T>
class Queue
{
public:
Queue();
Queue(const Queue& other);
~Queue();
void enqueue(T data);
T dequeue();
bool isEmpty() { return (front_ == back_); }
Queue& operator=(const Queue& other);
private:
struct node
{
T data;
node* next;
};
node* front_;
node* back_;
};
template <typename T>
Queue<T>::Queue()
{
front_ = new node();
back_ = front_;
}
template <typename T>
Queue<T>::Queue(const Queue<T>& other)
{
front_ = new node();
back_ = front_;
node* temp = other.front_;
while (temp != other.back_)
{
enqueue(temp->data);
temp = temp->next;
}
}
template <typename T>
Queue<T>::~Queue()
{
while (!isEmpty()) { dequeue(); }
}
template <typename T>
void Queue<T>::enqueue(T data)
{
back_->data = data;
back_->next = new node();
back_ = back_->next;
}
template <typename T>
T Queue<T>::dequeue()
{
assert(!isEmpty());
node* temp = front_;
T data = front_->data;
front_ = front_->next;
delete temp;
return data;
}
template <typename T>
Queue<T>& Queue<T>::operator=(const Queue<T>& other)
{
if (this != &other)
{
node* temp = other.front_;
while (!isEmpty()) { dequeue(); }
while (temp != other.back_)
{
enqueue(temp->data);
temp = temp->next;
}
}
return *this;
}
#endif