Adding a Node Before a Given Node
This is similar to adding a node after a given node,except that here we check that if the node to be added is the first node in the list.Here is the function
void addbefore(NODE *nodetoaddbefore,NODE* newnode) { //fn is passed a ptr to a NODE(add of) //,the node before which to add //node(nodetoaddbefore),and the add of the node to be //added(newnode) if(nodetoaddbefore)// NULL is not passed as the node to add before { NODE *temp=nodetoaddbefore; if(nodetoaddbefore!=first)//node before which to add is not the first node { temp->prev->next=newnode; newnode->next=temp; newnode->prev=temp->prev; temp->prev=newnode; } else { temp->prev->next=newnode; newnode->next=temp; newnode->prev=temp->prev; temp->prev=newnode; first=newnode; } 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(); } }
Deleting a specified node
The following function deletes a node whose address is passed as the argument.The following conditions are checked :-
- Node to be deleted is the only node in the list
- Node to be deleted is the first Node
- Node to be deleted is the last Node
- Node to be deleted is any other Node in between
Here is the function
void deletenode(NODE *nodetobedeleted) //fn is passed the add of node to be deleted { if(nodetobedeleted)//add passed is not NULL { if(nodetobedeleted==first && nodetobedeleted==last)//only node { delete nodetobedeleted; first=last=NULL; } else if(nodetobedeleted==first) { NODE *temp=first; first=first->next; delete temp; first->prev=NULL; } else if(nodetobedeleted==last) { NODE *temp=last; last=last->prev;//last changes last->next=NULL; delete temp;temp=NULL; } else // none of above,node in between { nodetobedeleted->prev->next=nodetobedeleted->next; nodetobedeleted->next->prev=nodetobedeleted->prev; delete nodetobedeleted;nodetobedeleted=NULL; } nodecount--; cout<<"\n\n\t\tDeleted ! Press a key to continue ...";getch(); } else { cout<<"\n\t\tcould not delete,Press a key to continue ... !";getch(); } }
Continue reading the remaining 3 pages of the article through page links below ....