The same thing is true . When you start working around some simple double linked list you are very closer towards implementing Binary tree and Binary search tree.The following is the basic doubly linked list implementation in C++ (Just an enhancement to previous singly linked list).


/* The simple double linear linked list program written in C/C++
This creates a head node of linked list first and insert the new nodes to the end of linked list .
You have to define the maximum size of linked list on start run .
This program is just a little enhancement of single linear linked list
*/
#include<iostream.h>

struct list
{
int value;
struct list * left;
struct list * right;
};

struct list * insert( struct list *, int);

int main()
{
struct list *head=(struct list *) malloc(sizeof(struct list));
cout <<"Enter the total no of nodes to be present in the linked list\n";
int total_element;
cin >> total_element;
cout<< "Enter the head value\n";
/* Create a head node and assign the value also assign the left and right node address to NULL (The linked list will end with a node whose next address is NULL */
cin >> head ->value;
head->left=NULL;
head->right=NULL;
for(int i=1;i<total_element;i++) {
cout<<"Enter the next node value \n";
int new1;
cin>>new1;
// The insert function gets the head pointer and new value as arguments
head= insert(head,new1);
}
// Start from the head and display all the nodes in the linked list till the node is NULL
struct list *disp=head;
struct list *disp_reverse;
cout <<" The display of the inserted doubly linked list from the first node \n";
// Start from the tail and display all the nodes in the linked list till the head
do{
cout<<"-->"<<disp->value;
disp_reverse = disp;
disp=disp->right;
}while (disp!=NULL);

cout <<" \nThe display of the inserted doubly linked list from the last node \n";
do{
cout<<"-->"<<disp_reverse->value;
disp_reverse=disp_reverse->left;
}while (disp_reverse!=NULL);
cout<<endl;

}
// Here we need to goto the end of the current linked list and create a new element and link there, finally return the head pointer
struct list * insert( struct list *head, int newvalue)
{
struct list *new1=(struct list *) malloc(sizeof(struct list));
struct list *temp = head;
while(temp->right!=NULL)
{
temp=temp->right;
}
new1 ->value=newvalue;
new1->right=NULL;
new1->left = temp;
temp->right=new1;
return head;
};

Related Posts :



Bookmark and Share