Searching for a node containing specific data item
NODE* search(int searchdata)//returns pointer to (add of )node with givendata //returns NULL for no match/no node exists { NODE *temp=first; if(temp) //if first node exists { while(temp)// runs untill temp becomes NULL { if (temp->data==searchdata) { return temp; // return the add of node where match found } else { temp=temp->next;// go to next node } } cout<<"\n\n\t\t Data not Found ! Press a key to continue ... to continue...";getch(); return temp ; // will return NULL at the end of last node } else { cout<<"\n\n\t\tNo Node Exists ! Press a key to continue ...";getch(); return NULL; } }
This function searches the complete linked list for a given data item passed as the argument and returns the address of the node if found,else returns the value in the *next pointer of the last node which is NULL.The entire linked list is traversed begining from the first node.
Adding a Node after a given Node in the List
The following function adds a node after a given node in the list
void addafter(NODE *nodetoaddafter,NODE *newnod) //fn is passed a ptr to a NODE(add of),the node after which to add //node(nodetoaddafter),and the add of the node to be //added(newnod) { if(nodetoaddafter)// NULL is not passed as the node to add after { NODE *temp; temp=nodetoaddafter; if(nodetoaddafter!=last)//node after which to add is not the last node { newnod->prev=nodetoaddafter; newnod->next=nodetoaddafter->next; temp->next=newnod; } else { newnod->prev=nodetoaddafter; newnod->next=nodetoaddafter->next; temp->next=newnod; last=newnod; } 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(); } }
In the above function,the memory address of the Node after which to add and the address of the new node to be added are passed in the argument.The function begins by checking that the nodetoaddafter is a valid node.If it is valid node the function checks if we are adding the new node after the last node in the double linked list.Either the newnode is added as the last node or somewhere in between.The *next and the *previous pointers of the node are accordingly manupulated.
Continue reading the remaining 4 pages of the article through page links below ....