Double linked list in c++ implementation

Adding a node at the head of the list

void addathead(NODE *temp)// this fn is passed pointer(an add of type NODE)
								  //and it links that node at the beg of list
{
	if(temp)//add passed is not NULLL
	{
		if(first==NULL)//node being linked is the first node in the list
		{
			first=last=temp;
		}
		else
		{
			temp->next=first;
			first->prev=temp;
			first=temp;

		}
    nodecount++;
    cout<<"\n\n\t\tAdded data to list. Press a key to continue ...";getch();


	}else
	{
	    cout<<"\n\n\t\tOut of Memory error. Node could not be added ! Press a key to continue ...";getch();
	}

}

To add a node at the head our function above adds the node passed in the argument to the head of the list.
In our main program,we shall use the two pointer variables of type NODE *first and *last holding the address of the first and the last node respectively,If the list was empty then first=last=NULL and this condition is checked in line 6.If the list was empty then the address of the new node passed to this function as argument is assigned to the pointer variable *first,i.e the new node becomes the first node. If not,i.e the first node already exists,then the node is added before the first node.The global variable nodecount in the calling program is incremented.

Add a node at tail of the double linked list

void addattail(NODE *temp)// this fn is passed pointer(an add of type NODE)
								  //and it links that node at the end of list
{
	if(temp)//add passed is not NULLL
	{
		if(first==NULL)//node being linked is the first node
		{
			first=last=temp;
		}
		else
		{
			temp->prev=last;
			last->next=temp;
			last=temp;
		}
	nodecount++;
    cout<<"\n\n\t\tAdded data to list. Press a key to continue ...";getch();
	}

	else
	{
	    cout<<"\n\n\t\tOut of Memory error. Node could not be added ! Press a key to continue ...";getch();
	}
}

Adding a node at the tail is similar,first a check is done whether the node presently being added is the first node,in that case it is added as the first node,else it is added o the end of the last node.In case there is only one node in the list then the first==last.The global variable nodecount in the calling program is incremented.


Continue reading the remaining 5 pages of the article through page links below ....

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.