I have written the code for linked list in c++. It has function list_search(int)
which returns the node of the given number. list_insertfront(int)
inserts the first element. list_insert(int)
inserts the element. list_delete(int)
deletes the element after searching its node.
#include <iostream>
class double_list{
struct Node{
int data;
struct Node *next; //next will hold the address and *next will show value at that address
struct Node *prev; //prev will hold the address and *prev will show value at that address
} *head;
public:
double_list(){
head=NULL; // all address in head are initialised to NULL
}
void list_insert(int);
void list_insertfront(int);
struct Node *list_search(int n){
Node *node =new Node();
node=head;
while(node!=NULL){
if(node->data==n) return node;
node=node->next;}
std::cout<<"No such elementin the list \n";
}
void list_delete(int);
void display();
};
void double_list::list_insertfront(int n){
Node *node=new Node();
node->data=n;
node->next=head;
head=node;
node->prev=NULL;
}
void double_list::list_insert(int n){
Node *node =new Node();
Node *temp =new Node();
node->data=n;
node->next=NULL;
temp=head;
while(temp){
if(temp->next==NULL){
temp->next=node;
break;
}
temp=temp->next;
}
}
void double_list::list_delete(int n){
Node *node=list_search(n);//to search node of the given number
Node *temp=new Node();
temp=head;
if(temp==node){
head=temp->next;
}
while(node!=NULL){
if(temp->next==node) temp->next=node->next;
temp=temp->next;
return;
}
}
void double_list::display(){
Node *node=new Node();
node =head;
while(node!=NULL){
std::cout<<node->data<<" ";
node=node->next;
}
}
int main()
{
double_list list1;
list1.list_insertfront(5);
list1.list_insert(1);
list1.list_insert(6);
list1.list_insert(7);
list1.display();
list1.list_delete(1);
std::cout<<"\n";
list1.display();
std::cout<<"\n";
return 0;
}
What should I do to improve this code.