TheAlgorithms-C-Plus-Plus/data_structure/cll/cll.cpp

134 lines
2.6 KiB
C++
Raw Normal View History

2020-01-08 07:57:31 +08:00
/*
A simple class for Cicular Linear Linked List
*/
#include "cll.h"
using namespace std;
/* Constructor */
cll::cll()
{
head = NULL;
total = 0;
}
cll::~cll() { /* Desstructure, no need to fill */ }
2020-01-08 07:57:31 +08:00
/* Display a list. and total element */
void cll::display()
{
if (head == NULL)
cout << "List is empty !" << endl;
else
{
cout << "CLL list: ";
node *current = head;
for (int i = 0; i < total; i++)
{
cout << current->data << " -> ";
current = current->next;
2020-01-08 07:57:31 +08:00
}
cout << head->data << endl;
cout << "Total element: " << total << endl;
2020-01-08 07:57:31 +08:00
}
}
/* List insert a new value at head in list */
void cll::insert_front(int new_data)
{
node *newNode;
newNode = new node;
newNode->data = new_data;
newNode->next = NULL;
if (head == NULL)
{
2020-01-08 07:57:31 +08:00
head = newNode;
head->next = head;
}
else
{
2020-01-08 07:57:31 +08:00
node *current = head;
while (current->next != head)
{
2020-01-08 07:57:31 +08:00
current = current->next;
}
newNode->next = head;
current->next = newNode;
head = newNode;
}
total++;
}
/* List insert a new value at head in list */
void cll::insert_tail(int new_data)
{
node *newNode;
newNode = new node;
newNode->data = new_data;
newNode->next = NULL;
if (head == NULL)
{
2020-01-08 07:57:31 +08:00
head = newNode;
head->next = head;
}
else
{
2020-01-08 07:57:31 +08:00
node *current = head;
while (current->next != head)
{
2020-01-08 07:57:31 +08:00
current = current->next;
}
current->next = newNode;
newNode->next = head;
}
total++;
}
/* Get total element in list */
int cll::get_size() { return total; }
2020-01-08 07:57:31 +08:00
/* Return true if the requested item (sent in as an argument)
is in the list, otherwise return false */
bool cll::find_item(int item_to_find)
{
if (head == NULL)
{
2020-01-08 07:57:31 +08:00
cout << "List is empty !" << endl;
return false;
}
else
{
2020-01-08 07:57:31 +08:00
node *current = head;
while (current->next != head)
{
2020-01-08 07:57:31 +08:00
if (current->data == item_to_find)
return true;
current = current->next;
}
return false;
}
}
/* Overloading method*/
int cll::operator*() { return head->data; }
2020-01-08 07:57:31 +08:00
/* Overload the pre-increment operator.
The iterator is advanced to the next node. */
void cll::operator++()
{
if (head == NULL)
{
2020-01-08 07:57:31 +08:00
cout << "List is empty !" << endl;
}
else
{
2020-01-08 07:57:31 +08:00
node *current = head;
while (current->next != head)
{
current = current->next;
2020-01-08 07:57:31 +08:00
}
current->next = head->next;
head = head->next;
2020-01-08 07:57:31 +08:00
}
total--;
}