I want to improve this code.
#include <iostream>
#include <utility>
template <class T>
class circular_linked_list
{
struct Node
{
T data;
Node * next;
Node(T value) : data(std::move(value)), next(nullptr) {}
};
Node *head;
public:
circular_linked_list() : head(nullptr) {}
circular_linked_list(const circular_linked_list& cll) = delete; //copy constructor
circular_linked_list(circular_linked_list&& cll) = delete; //move constructor
circular_linked_list& operator=(const circular_linked_list& cll) = delete; //copy assignment
circular_linked_list& operator=(circular_linked_list&& cll) = delete; //move assignment
~circular_linked_list();
void insert_at_begin(T);
void insert_at_end(T);
void delete_node(T);
void print_list();
private:
struct Node *search(T value)
{
Node *node = head;
while(node->next != head)
{
if(node->data == value)
return node;
node = node->next;
}
std::cerr << "No such element in the List \n";
return nullptr;
}
};
template <class T>
void circular_linked_list<T>::insert_at_begin(T value)
{
Node *node = new Node(std::move(value));
if(head == nullptr)
{
node->next = node;
head = node;
return;
}
Node *tmp = head;
while(tmp->next != head)
{
tmp = tmp->next;
}
tmp->next = node;
node->next = head;
head = node;
}
template <class T>
void circular_linked_list<T>::insert_at_end(T value)
{
Node *node = new Node(std::move(value));
if(head == nullptr)
{
node->next = node;
head = node;
return;
}
Node *tmp = head;
while(tmp->next != head)
{
tmp = tmp->next;
}
tmp->next = node;
node->next = head;
}
template <class T>
void circular_linked_list<T>::delete_node(T value)
{
Node *node = search(value);
Node *tmp = head;
Node *tail = head;
while(tail->next != head)
{
tail = tail->next;
}
if(tmp == node)
{
head = tmp->next; //deleting first element
tail->next = head;
}
else
{
while(node != nullptr)
{
if(tmp->next == node)
{
tmp->next = node->next;
return;
}
tmp = tmp->next;
}
}
delete tmp;
}
template <class T>
void circular_linked_list<T>::print_list()
{
Node *tmp = head;
while(tmp->next != head)
{
std::cout << tmp->data << ' ';
tmp = tmp->next;
}
std::cout << tmp->data << '\n';
}
template <class T>
circular_linked_list<T>::~circular_linked_list()
{
Node *tmp = nullptr;
Node *tail = head;
while(tail->next != head)
{
tail = tail->next;
}
tail->next = nullptr;
while(head != nullptr)
{
tmp = head;
head = head->next;
delete tmp;
}
}
int main()
{
circular_linked_list<int> cll1;
cll1.insert_at_end(2);
cll1.insert_at_end(3);
cll1.insert_at_end(4);
cll1.insert_at_begin(1);
cll1.insert_at_begin(0);
cll1.print_list();
cll1.delete_node(2);
cll1.print_list();
}