Seeking recommendations on how to improve this code, LL always seem to be a struggle.
A basic linked list that does include next and previous pointers. I used a struct inside of a class, which I'm not sure if that's frowned upon. The program includes 5 basic member functions, one to add to the head of the list, one to add to the tail of the list, one to delete the head, one to delete any index, one that checks the list for duplicate data (based on the data variable in the struct), and a print. Everything works as it should, but I'm just not sure if I was efficient, in fact I'm pretty sure I wasn't. Sorry If im forgetting something, but I'm new here!
1.
class list
{
private:
struct node
{
int data;
node* next;
node* prev;
};
typedef node* nodePtr;
nodePtr head;
nodePtr temp;
nodePtr prev;
public:
list();
void add_to_head(int);
void add_to_tail(int);
void delete_index(int);
void check_duplicates(int);
void print();
};
2.
#include <iostream>
using std:: cout;
using std:: endl;
list::list(void)
{
head = NULL;
temp = NULL;
prev = NULL;
}
void list:: add_to_head(int num)
{
nodePtr n = new node;
n->data = num;
if(head == NULL)
{
n->prev = NULL;
n->next = NULL;
head = n;
}
else
{
n->next = head;
n->prev = NULL;
head = n;
}
return;
}
void list::add_to_tail(int num)
{
nodePtr n = new node;
n->data = num;
if(head == NULL)
{
n->prev = NULL;
n->next = NULL;
head = n;
}
else
{
temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
n->prev = temp;
n->next = NULL;
}
return;
}
void list::delete_index(int index)
{
if(index == 0)
{
temp = head->next;
temp ->prev = NULL;
prev = head;
delete prev;
head = temp;
}
else
{
nodePtr del = new node;
int count =0;
temp = head;
while(count != index)
{
prev = temp;
temp = temp->next;
count++;
}
del = temp;
if(temp->next == NULL)
{
prev->next = NULL;
}
else
{
prev->next = temp->next;
temp = temp->next;
temp->prev = prev;
}
delete del;
}
return;
}
void list::check_duplicates(int num)
{
int count = -1;
temp = head;
while(temp != NULL)
{
if(temp->data == num)
{
count++;
}
temp = temp->next;
}
if(count > 0)
{
cout<<endl<<endl<<"The number "<<num<<" was found "<<count + 1<<" times."<<endl;
}
else if(count == -1)
{
if(head == NULL)
{
cout<<"The list is empty."<<endl;
}
else
{
cout<<"The number was not found within the list."<<endl;
}
}
return;
}
void list::print()
{
temp = head;
cout<<endl<<"The list:"<<endl;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
return;
}