id
int64
0
25.6k
text
stringlengths
0
4.59k
24,400
data structures using return start/had to be added output *****main menu **** create list display the list add node at the beginning add the node at the end add the node before given node add the node after given node delete node from the beginning delete node from the end delete given node delete node after given node delete the entire list sort the list exit enter your option enter your option circular linked lists in circular linked listthe last node contains pointer to the first node of the list we can have circular singly linked list as well as circular doubly linked list while traversing circular linked listwe can begin at any node and traverse the list in any directionforward or backwarduntil we reach the same node where we started thusa circular linked list has no beginning and no ending figure shows circular linked list start figure circular linked list the only downside of circular linked list is the complexity of iteration note that there are no null values in the next part of any of the nodes of list circular linked lists are widely used in operating systems for task start maintenance we will now discuss an example where circular linked next data list is used when we are surfing the internetwe can use the back button and the forward button to move to the previous pages that we have already visited how is this donethe answer is simple circular linked list is used to maintain the sequence of the web pages visited traversing this circular linked list either in forward or backward direction helps to revisit the pages again using back and forward buttons actuallythis is done using either the circular stack or the circular queue we will read about circular queues in consider fig we can traverse the list until we find the next entry that contains the address of the first node of the list this denotes the end of the linked figure memory representation listthat isthe node that contains the address of the first node is actually of circular linked list
24,401
start (biology start (computer science figure roll no next memory representation of two circular linked lists stored in the memory the last node of the list when we traverse the data and next in this mannerwe will finally see that the linked list in fig stores characters that when put together form the word hello nowlook at fig two different linked lists are simultaneously maintained in the memory there is no ambiguity in traversing through the list because each list maintains separate start pointer which gives the address of the first node of the respective linked list the remaining nodes are reached by looking at the value stored in next by looking at the figurewe can conclude that the roll numbers of the students who have opted for biology are and similarlythe roll numbers of the students who chose computer science are and inserting new node in circular linked list in this sectionwe will see how new node is added into an already existing linked list we will take two cases and then see how insertion is done in each case case the new node is inserted at the beginning of the circular linked list case the new node is inserted at the end of the circular linked list inserting node at the beginning of circular linked list consider the linked list shown in fig suppose we want to add new node with data as the first node of the list then the following changes will be done in the linked list start allocate memory for the new node and initialize its data part to take pointer variable ptr that points to the start node of the list start ptr move ptr so that it now points to the last node of the list start add the new node in between ptr and start ptr ptr start make start point to the new node start figure inserting new node at the beginning of circular linked list
24,402
data structures using figure shows the algorithm to insert new node at the beginning of linked list in step we first check whether memory is available for the new node if the free memory has exhaustedthen an overflow message is printed otherwiseif free memory cell is availablethen we allocate space for the new node set its data part with the given val and the next part is initialized with the address of the first node of the listwhich is stored in start nowsince the new node is added as the first node of the listit will now be known as the start nodethat isthe start pointer variable will now hold figure algorithm to insert new node at the beginning the address of the new_node while inserting node in circular linked listwe have to use while loop to traverse to the last node of the list because the last node contains pointer to startits next field is updated so that after insertion it points to the new node which will be now known as start step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set ptr start step repeat step while ptr -next !start step ptr ptr -next [end of loopstep set new_node -next start step set ptr -next new_node step set start new_node step exit inserting node at the end of circular linked list consider the linked list shown in fig suppose we want to add new node with data as the last node of the list then the following changes will be done in the linked list start allocate memory for the new node and initialize its data part to take pointer variable ptr which will initially point to start ptr startmove ptr so that it now points to the last node of the list start ptr add the new node after the node pointed by ptr start ptr figure inserting new node at the end of circular linked list figure shows the algorithm to insert new node at the end of circular linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe traverse through the linked list to reach the last node once we reach the last nodein step we change the next pointer of the last node to store the address of the new node remember that the next field of the new node contains the address of the first node which is denoted by start deleting node from circular linked list in this sectionwe will discuss how node is deleted from an already existing circular linked list we will take two cases and then see how deletion is done in each case rest of the cases of
24,403
deletion are same as that given for singly linked lists step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set new_node -next start step set ptr start step repeat step while ptr -next !start step set ptr ptr -next [end of loopstep set ptr -next new_node step exit figure case the first node is deleted case the last node is deleted deleting the first node from circular linked list consider the circular linked list shown in fig when we want to delete node from the beginning of the listthen the following changes will be done in the linked list algorithm to insert new node at the end start take variable ptr and make it point to the start node of the list start ptr move ptr further so that it now points to the last node of the list ptr start the next part of ptr is made to point to the second node of the list and the memory of the first node is freed the second node becomes the first node of the list ptr start figure deleting the first node from circular linked list figure shows the algorithm to delete the first node from circular linked list in step of the algorithmwe check if the linked list exists or not if start nullthen it signifies that there are no nodes in the list and the control is transferred to the last statement of the algorithm howeverif there are nodes in the linked listthen we use pointer variable ptr which will be used to traverse the list to ultimately reach the last node in step we change the next pointer of the last node to point to the second node of step if start null the circular linked list in step the memory write underflow occupied by the first node is freed finallyin go to step step the second node now becomes the first [end of ifstep set ptr start node of the list and its address is stored in the step repeat step while ptr -next !start pointer variable start step set ptr ptr -next [end of loopstep set ptr -next start -next step free start step set start ptr -next step exit figure algorithm to delete the first node deleting the last node from circular linked list consider the circular linked list shown in fig suppose we want to delete the last node from the linked listthen the following changes will be done in the linked list
24,404
data structures using start take two pointers preptr and ptr which will initially point to start start preptr ptr move ptr so that it points to the last node of the list preptr will always point to the node preceding ptr preptr ptr start make the preptr' next part store start node' address and free the space allocated for ptr now preptr is the last node of the list start preptr figure deleting the last node from circular linked list step if start null write underflow go to step [end of ifstep set ptr start step repeat steps and while ptr -next !start step set preptr ptr step set ptr ptr -next [end of loopstep set preptr -next start step free ptr step exit figure algorithm to delete the last node figure shows the algorithm to delete the last node from circular linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe take another pointer variable preptr such that preptr always points to one node before ptr once we reach the last node and the second last nodewe set the next pointer of the second last node to startso that it now becomes the (newlast node of the linked list the memory of the previous last node is freed and returned to the free pool programming example write program to create circular linked list perform insertion and deletion at the beginning and end of the list #include #include #include struct node int datastruct node *next}struct node *start nullstruct node *create_cll(struct node *)struct node *display(struct node *)struct node *insert_beg(struct node *)struct node *insert_end(struct node *)
24,405
struct node *delete_beg(struct node *)struct node *delete_end(struct node *)struct node *delete_after(struct node *)struct node *delete_list(struct node *)int main(int optionclrscr()do printf("\ \ *****main menu *****")printf("\ create list")printf("\ display the list")printf("\ add node at the beginning")printf("\ add node at the end")printf("\ delete node from the beginning")printf("\ delete node from the end")printf("\ delete node after given node")printf("\ delete the entire list")printf("\ exit")printf("\ \ enter your option ")scanf("% "&option)switch(optioncase start create_cll(start)printf("\ circular linked list created")breakcase start display(start)breakcase start insert_beg(start)breakcase start insert_end(start)breakcase start delete_beg(start)breakcase start delete_end(start)breakcase start delete_after(start)breakcase start delete_list(start)printf("\ circular linked list deleted")break}while(option != )getch()return struct node *create_cll(struct node *startstruct node *new_node*ptrint numprintf("\ enter - to end")printf("\ enter the data ")scanf("% "&num)while(num!=- new_node (struct node*)malloc(sizeof(struct node))new_node -data numif(start =nullnew_node -next new_node
24,406
data structures using start new_nodeelse ptr startwhile(ptr -next !startptr ptr -nextptr -next new_nodenew_node -next startprintf("\ enter the data ")scanf("% "&num)return startstruct node *display(struct node *startstruct node *ptrptr=startwhile(ptr -next !startprintf("\ % "ptr -data)ptr ptr -nextprintf("\ % "ptr -data)return startstruct node *insert_beg(struct node *startstruct node *new_node*ptrint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -next !startptr ptr -nextptr -next new_nodenew_node -next startstart new_nodereturn startstruct node *insert_end(struct node *startstruct node *ptr*new_nodeint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -next !startptr ptr -nextptr -next new_nodenew_node -next startreturn startstruct node *delete_beg(struct node *startstruct node *ptrptr start
24,407
while(ptr -next !startptr ptr -nextptr -next start -nextfree(start)start ptr -nextreturn startstruct node *delete_end(struct node *startstruct node *ptr*preptrptr startwhile(ptr -next !startpreptr ptrptr ptr -nextpreptr -next ptr -nextfree(ptr)return startstruct node *delete_after(struct node *startstruct node *ptr*preptrint valprintf("\ enter the value after which the node has to deleted ")scanf("% "&val)ptr startpreptr ptrwhile(preptr -data !valpreptr ptrptr ptr -nextpreptr -next ptr -nextif(ptr =startstart preptr -nextfree(ptr)return startstruct node *delete_list(struct node *startstruct node *ptrptr startwhile(ptr -next !startstart delete_end(start)free(start)return startoutput *****main menu **** create list display the list add node at the beginning delete the entire list exit enter your option enter - to end enter the data enter the data
24,408
data structures using enter the data enter the data- circular linked list created enter your option enter your option enter your option enter your option doubly linked lists doubly linked list or two-way linked list is more complex type of linked list which contains pointer to the next as well as the previous node in the sequence thereforeit consists of three parts--dataa pointer to the next nodeand pointer to the previous node as shown in fig start figure doubly linked list in cthe structure of doubly linked list can be given asstruct node struct node *prevint datastruct node *next}start the prev field of the first node and the next field of the last node will contain null the prev field is used to store the address of the preceding nodewhich enables us to traverse the list in the backward direction thuswe see that doubly linked list calls for more space per node and more expensive basic operations howevera doubly linked list provides the ease to manipulate the elements of the list as it maintains pointers to nodes in both the directions (forward and backwardthe main advantage of using doubly linked list is that it makes searching twice as efficient let us view how doubly linked list is maintained in the memory consider fig in the figurewe see that variable start is used to store the address of the first node in this examplestart so the first data is stored at address which is since this is the first nodeit has no previous node and hence prev data next stores null or - in the prev field we will traverse the list until - we reach position where the next entry contains - or null this denotes the end of the linked list when we traverse the data and next in this mannerwe will finally see that the linked list in the above example stores characters that when put together form the word hello - figure memory representation of doubly linked list inserting new node in doubly linked list in this sectionwe will discuss how new node is added into an already existing doubly linked list we will take four cases and then see how insertion is done in each case case the new node is inserted at the beginning
24,409
case the new node is inserted at the end case the new node is inserted after given node case the new node is inserted before given node inserting node at the beginning of doubly linked list consider the doubly linked list shown in fig suppose we want to add new node with data as the first node of the list then the following changes will be done in the linked list start allocate memory for the new node and initialize its data part to and prev field to null add the new node before the start node now the new node becomes the first node of the list start figure inserting new node at the beginning of doubly linked list step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set new_node -prev null step set new_node -next start step set start -prev new_node step set start new_node step exit figure algorithm to insert new node at the beginning figure shows the algorithm to insert new node at the beginning of doubly linked list in step we first check whether memory is available for the new node if the free memory has exhaustedthen an overflow message is printed otherwiseif free memory cell is availablethen we allocate space for the new node set its data part with the given val and the next part is initialized with the address of the first node of the listwhich is stored in start nowsince the new node is added as the first node of the listit will now be known as the start nodethat isthe start pointer variable will now hold the address of new_node inserting node at the end end of doubly linked list consider the doubly linked list shown in fig suppose we want to add new node with data as the last node of the list then the following changes will be done in the linked list start allocate memory for the new node and initialize its data part to and its next field to null take pointer variable ptr and make it point to the first node of the list start,ptr move ptr so that it points to the last node of the list add the new node after the node pointed by ptr start figure inserting new node at the end of doubly linked list ptr
24,410
data structures using figure shows the algorithm to insert new node at the end of doubly linked list in step we take pointer variable ptr and initialize it with start in the while loopwe traverse through the linked list to reach the last node once we reach the last nodein step we change the next pointer of the last node to store the address of the new node remember that the next field of the new node contains null which signifies the end of the linked list the prev field of the new_node will be set so that it points to the node pointed by ptr (now the second last node of the liststep if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set new_node -next null step set ptr start step repeat step while ptr -next !null step set ptr ptr -next [end of loopstep set ptr -next new_node step set new_node -prev ptr step exit figure algorithm to insert new node at the end step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set ptr start step repeat step while ptr -data !num step set ptr ptr -next [end of loopstep set new_node -next ptr -next step set new_node -prev ptr step set ptr -next new_node step set ptr -next -prev new_node step exit figure algorithm to insert new node after given node inserting node after given node in doubly linked list consider the doubly linked list shown in fig suppose we want to add new node with value after the node containing before discussing the changes that will be done in the linked listlet us first look at the algorithm shown in fig start allocate memory for the new node and initialize its data part to take pointer variable ptr and make it point to the first node of the list start,ptr move ptr further until the data part of ptr value after which the node has to be inserted start ptr insert the new node between ptr and the node succeeding it ptr start start figure inserting new node after given node in doubly linked list
24,411
step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set ptr start step repeat step while ptr -data !num step set ptr ptr -next [end of loopstep set new_node -next ptr step set new_node -prev ptr -prev step set ptr -prev new_node step set ptr -prev -next new_node step exit figure shows the algorithm to insert new node after given node in doubly linked list in step we take pointer ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe traverse through the linked list to reach the node that has its value equal to num we need to reach this node because the new node will be inserted after this node once we reach this nodewe change the next and prev fields in such way that the new node is inserted after the desired node inserting node before given node in doubly linked list consider the doubly linked list shown in fig figure algorithm to insert new node before suppose we want to add new node with value given node before the node containing before discussing the changes that will be done in the linked listlet us first look at the algorithm shown in fig in step we first check whether memory is available for the new node in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe traverse through the linked list to reach the node that has its value equal to num we need to reach this node because the new node will be inserted before this node once we reach this nodewe change the next and prev fields in such way that the new node is inserted before the desired node start allocate memory for the new node and initialize its data part to take pointer variable ptr and make it point to the first node of the list startptr move ptr further so that it now points to the node whose data is equal to the value before which the node has to be inserted start add the new node in between the node pointed by ptr and the node preceding it ptr ptr start start figure inserting new node before given node in doubly linked list deleting node from doubly linked list in this sectionwe will see how node is deleted from an already existing doubly linked list we will take four cases and then see how deletion is done in each case
24,412
data structures using case the first node is deleted case the last node is deleted case the node after given node is deleted case the node before given node is deleted deleting the first node from doubly linked list consider the doubly linked list shown in fig when we want to delete node from the beginning of the listthen the following changes will be done in the linked list start free the memory occupied by the first node of the list and make the second node of the list as the start node start figure deleting the first node from doubly linked list figure shows the algorithm to delete the first node of doubly linked list in step of the algorithmwe check if the linked list exists or not if start nullthen it signifies that there are no nodes in the list and the step if start null control is transferred to the last statement of the algorithm write underflow go to step howeverif there are nodes in the linked listthen we use [end of ifa temporary pointer variable ptr that is set to point to the first step set ptr start step set start start -next node of the list for thiswe initialize ptr with start that stores step set start -prev null the address of the first node of the list in step start is made step free ptr to point to the next node in sequence and finally the memory step exit occupied by ptr (initially the first node of the listis freed and figure algorithm to delete the first node returned to the free pool deleting the last node from doubly linked list consider the doubly linked list shown in fig suppose we want to delete the last node from the linked listthen the following changes will be done in the linked list start take pointer variable ptr that points to the first node of the list start,ptr move ptr so that it now points to the last node of the list ptr start free the space occupied by the node pointed by ptr and store null in next field of its preceding node start figure deleting the last node from doubly linked list
24,413
step if start null write underflow go to step [end of ifstep set ptr start step repeat step while ptr -next !null step set ptr ptr -next [end of loopstep set ptr -prev -next null step free ptr step exit figure algorithm to delete the last node figure shows the algorithm to delete the last node of doubly linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list the while loop traverses through the list to reach the last node once we reach the last nodewe can also access the second last node by taking its address from the prev field of the last node to delete the last nodewe simply have to set the next field of second last node to nullso that it now becomes the (newlast node of the linked list the memory of the previous last node is freed and returned to the free pool deleting the node after given node in doubly linked list consider the doubly linked list shown in fig suppose we want to delete the node that succeeds the node which contains data value then the following changes will be done in the linked list start take pointer variable ptr and make it point to the first node of the list start,ptr move ptr further so that its data part is equal to the value after which the node has to be inserted start delete the node succeeding ptr ptr start ptr start figure deleting the node after given node in doubly linked list step if start null write underflow go to step [end of ifstep set ptr start step repeat step while ptr -data !num step set ptr ptr -next [end of loopstep set temp ptr -next step set ptr -next temp -next step set temp -next -prev ptr step free temp step exit figure algorithm to delete node after given node figure shows the algorithm to delete node after given node of doubly linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the doubly linked list the while loop traverses through the linked list to reach the given node once we reach the node containing valthe node succeeding it can be easily accessed by using the address stored in its next field the next field of the given node is set to contain the contents in the next field of the succeeding node finallythe memory of the node succeeding the given node is freed and returned to the free pool
24,414
data structures using deleting the node before given node in doubly linked list consider the doubly linked list shown in fig suppose we want to delete the node preceding the node with value before discussing the changes that will be done in the linked listlet us first look at the algorithm start take pointer variable ptr that points to the first node of the list start,ptr move ptr further till its data part is equal to the value before which the node has to be deleted ptr start delete the node preceding ptr ptr start start figure deleting node before given node in doubly linked list figure shows the algorithm to delete node before given node of doubly linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list the while loop traverses through the linked list to reach the desired node once we reach the node containing valthe prev field of ptr is set to contain the address of the node preceding the node which comes before ptr the memory of the node preceding ptr is freed and returned to the free pool hencewe see that we can insert or delete node figure algorithm to delete node before given in constant number of operations given only that node node' address note that this is not possible in the case of singly linked list which requires the previous node' address also to perform the same operation step if start null write underflow go to step [end of ifstep set ptr start step repeat step while ptr -data !num step set ptr ptr -next [end of loopstep set temp ptr -prev step set temp -prev -next ptr step set ptr -prev temp -prev step free temp step exit programming example write program to create doubly linked list and perform insertions and deletions in all cases #include #include #include
24,415
struct node struct node *nextint datastruct node *prev}struct node *start nullstruct node *create_ll(struct node *)struct node *display(struct node *)struct node *insert_beg(struct node *)struct node *insert_end(struct node *)struct node *insert_before(struct node *)struct node *insert_after(struct node *)struct node *delete_beg(struct node *)struct node *delete_end(struct node *)struct node *delete_before(struct node *)struct node *delete_after(struct node *)struct node *delete_list(struct node *)int main(int optionclrscr()do printf("\ \ *****main menu *****")printf("\ create list")printf("\ display the list")printf("\ add node at the beginning")printf("\ add node at the end")printf("\ add node before given node")printf("\ add node after given node")printf("\ delete node from the beginning")printf("\ delete node from the end")printf("\ delete node before given node")printf("\ delete node after given node")printf("\ delete the entire list")printf("\ exit")printf("\ \ enter your option ")scanf("% "&option)switch(optioncase start create_ll(start)printf("\ doubly linked list created")breakcase start display(start)breakcase start insert_beg(start)breakcase start insert_end(start)breakcase start insert_before(start)breakcase start insert_after(start)breakcase start delete_beg(start)breakcase start delete_end(start)breakcase start delete_before(start)breakcase start delete_after(start)
24,416
data structures using breakcase start delete_list(start)printf("\ doubly linked list deleted")break}while(option ! )getch()return struct node *create_ll(struct node *startstruct node *new_node*ptrint numprintf("\ enter - to end")printf("\ enter the data ")scanf("% "&num)while(num !- if(start =nullnew_node (struct node*)malloc(sizeof(struct node))new_node -prev nullnew_node -data numnew_node -next nullstart new_nodeelse ptr=startnew_node (struct node*)malloc(sizeof(struct node))new_node->data=numwhile(ptr->next!=nullptr ptr->nextptr->next new_nodenew_node->prev=ptrnew_node->next=nullprintf("\ enter the data ")scanf("% "&num)return startstruct node *display(struct node *startstruct node *ptrptr=startwhile(ptr!=nullprintf("\ % "ptr -data)ptr ptr -nextreturn startstruct node *insert_beg(struct node *startstruct node *new_nodeint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data num
24,417
start -prev new_nodenew_node -next startnew_node -prev nullstart new_nodereturn startstruct node *insert_end(struct node *startstruct node *ptr*new_nodeint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr=startwhile(ptr -next !nullptr ptr -nextptr -next new_nodenew_node -prev ptrnew_node -next nullreturn startstruct node *insert_before(struct node *startstruct node *new_node*ptrint numvalprintf("\ enter the data ")scanf("% "&num)printf("\ enter the value before which the data has to be inserted ")scanf("% "&val)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -data !valptr ptr -nextnew_node -next ptrnew_node -prev ptr-prevptr -prev -next new_nodeptr -prev new_nodereturn startstruct node *insert_after(struct node *startstruct node *new_node*ptrint numvalprintf("\ enter the data ")scanf("% "&num)printf("\ enter the value after which the data has to be inserted ")scanf("% "&val)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -data !valptr ptr -nextnew_node -prev ptrnew_node -next ptr -nextptr -next -prev new_nodeptr -next new_nodereturn start
24,418
data structures using struct node *delete_beg(struct node *startstruct node *ptrptr startstart start -nextstart -prev nullfree(ptr)return startstruct node *delete_end(struct node *startstruct node *ptrptr startwhile(ptr -next !nullptr ptr -nextptr -prev -next nullfree(ptr)return startstruct node *delete_after(struct node *startstruct node *ptr*tempint valprintf("\ enter the value after which the node has to deleted ")scanf("% "&val)ptr startwhile(ptr -data !valptr ptr -nexttemp ptr -nextptr -next temp -nexttemp -next -prev ptrfree(temp)return startstruct node *delete_before(struct node *startstruct node *ptr*tempint valprintf("\ enter the value before which the node has to deleted ")scanf("% "&val)ptr startwhile(ptr -data !valptr ptr -nexttemp ptr -previf(temp =startstart delete_beg(start)else ptr -prev temp -prevtemp -prev -next ptrfree(temp)return startstruct node *delete_list(struct node *startwhile(start !nullstart delete_beg(start)return start
24,419
output *****main menu **** create list display the list delete the entire list exit enter your option enter - to end enter the data enter the data enter the data enter the data- doubly linked list created enter your option circular doubly linked lists circular doubly linked list or circular two-way linked list is more complex type of linked list which contains pointer to the next as well as the previous node in the sequence the difference between doubly linked and circular doubly linked list is same as that exists between singly linked list and circular linked list the circular doubly linked list does not contain null in the previous field of the first node and the next field of the last node ratherthe next field of the last node stores the address of the first node of the listi start similarlythe previous field of the first field stores the address of the last node circular doubly linked list is shown in fig start figure circular doubly linked list since circular doubly linked list contains three parts in its structureit calls for more space per node and more expensive basic operations howevera circular doubly linked list provides the ease to manipulate the elements of the list as it maintains pointers to nodes in both the directions (forward and backwardthe main advantage of using circular doubly linked list is that it makes search operation twice as efficient let us view how circular doubly linked list is maintained in the start memory consider fig in the figurewe see that variable prev data next start is used to store the address of the first node here in this examplestart so the first data is stored at address which is since this is the first nodeit stores the address of the last node of the list in its previous field the corresponding next stores the address of the next nodewhich is sowe will look at address to fetch the next data item the previous field will contain the address of the first node the second data element obtained from address is we repeat this procedure until we reach position where the next entry stores the address of the first element of the list this denotes the end of the linked listthat isthe node that contains the address of the first node is actually the last node of figure memory representation of the list circular doubly linked list
24,420
data structures using inserting new node in circular doubly linked list in this sectionwe will see how new node is added into an already existing circular doubly linked list we will take two cases and then see how insertion is done in each case rest of the cases are similar to that given for doubly linked lists case the new node is inserted at the beginning case the new node is inserted at the end inserting node at the beginning of circular doubly linked list consider the circular doubly linked list shown in fig suppose we want to add new node with data as the first node of the list thenthe following changes will be done in the linked list start allocate memory for the new node and initialize its data part to take pointer variable ptr that points to the first node of the list start,ptr move ptr so that it now points to the last node of the list insert the new node in between ptr and the start node ptr start start will now point to the new node start figure inserting new node at the beginning of circular doubly linked list figure shows the algorithm to insert step if avail null write overflow new node at the beginning of circular doubly go to step linked list in step we first check whether [end of ifmemory is available for the new node if the free step set new_node avail step set avail avail -next memory has exhaustedthen an overflow message step set new_node -data val is printed otherwisewe allocate space for the step set ptr start new node set its data part with the given val and step repeat step while ptr -next !start its next part is initialized with the address of the step set ptr ptr -next [end of loopfirst node of the listwhich is stored in start step set ptr -next new_node now since the new node is added as the first node step set new_node -prev ptr of the listit will now be known as the start nodestep set new_node -next start that isthe start pointer variable will now hold step set start -prev new_node step set start new_node the address of new_node since it is circular step exit doubly linked listthe prev field of the new_node figure algorithm to insert new node at the beginning is set to contain the address of the last node
24,421
inserting node at the end of circular doubly linked list consider the circular doubly linked list shown in fig suppose we want to add new node with data as the last node of the list then the following changes will be done in the linked list start allocate memory for the new node and initialize its data part to take pointer variable ptr that points to the first node of the list startptr move ptr to point to the last node of the list so that the new node can be inserted after it ptr start figure inserting new node at the end of circular doubly linked list figure shows the algorithm to insert new node at the end of circular doubly linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list in the while loopwe traverse through the linked list to reach the last node once we reach the last nodein step we change the next pointer of the last node to store the address of the new node the prev field of the new_node will be set so that it points to the node pointed by ptr (now the second last node of the listdeleting node from circular doubly linked list in this sectionwe will see how node is deleted from an already existing circular doubly linked list we will take two cases and then see how deletion is done in each case rest of the cases are same as that given for doubly linked lists case the first node is deleted step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set new_node -data val step set new_node -next start step set ptr start step repeat step while ptr -next !start step set ptr ptr -next [end of loopstep set ptr -next new_node step set new_node -prev ptr step set start -prev new_node step exit figure algorithm to insert new node at the end case the last node is deleted deleting the first node from circular doubly linked list consider the circular doubly linked list shown in fig when we want to delete node from the beginning of the listthen the following changes will be done in the linked list figure shows the algorithm to delete the first node from circular doubly linked list in step of the algorithmwe check if the linked list exists or not if start nullthen it signifies that there are no nodes in the list and the control is transferred to the last statement of the algorithm
24,422
data structures using start take pointer variable ptr that points to the first node of the list startptr move ptr further so that it now points to the last node of the list ptr start make start point to the second node of the list free the space occupied by the first node start figure deleting the first node from circular doubly linked list step if start null write underflow go to step [end of ifstep set ptr start step repeat step while ptr -next !start step set ptr ptr -next [end of loopstep set ptr -next start -next step set start -next -prev ptr step free start step set start ptr -next figure algorithm to delete the first node howeverif there are nodes in the linked listthen we use pointer variable ptr that is set to point to the first node of the list for thiswe initialize ptr with start that stores the address of the first node of the list the while loop traverses through the list to reach the last node once we reach the last nodethe next pointer of ptr is set to contain the address of the node that succeeds start finallystart is made to point to the next node in the sequence and the memory occupied by the first node of the list is freed and returned to the free pool deleting the last node from circular doubly linked list consider the circular doubly linked list shown in fig suppose we want to delete the last node from the linked listthen the following changes will be done in the linked list start take pointer variable ptr that points to the first node of the list startptr move ptr further so that it now points to the last node of the list free the space occupied by ptr ptr start start figure deleting the last node from circular doubly linked list
24,423
step if start null write underflow go to step [end of ifstep set ptr start step repeat step while ptr -next !start step set ptr ptr -next [end of loopstep set ptr -prev -next start step set start -prev ptr -prev step free ptr step exit figure algorithm to delete the last node figure shows the algorithm to delete the last node from circular doubly linked list in step we take pointer variable ptr and initialize it with start that isptr now points to the first node of the linked list the while loop traverses through the list to reach the last node once we reach the last nodewe can also access the second last node by taking its address from the prev field of the last node to delete the last nodewe simply have to set the next field of the second last node to contain the address of startso that it now becomes the (newlast node of the linked list the memory of the previous last node is freed and returned to the free pool programming example write program to create circular doubly linked list and perform insertions and deletions at the beginning and end of the list #include #include #include struct node struct node *nextint datastruct node *prev}struct node *start nullstruct node *create_ll(struct node *)struct node *display(struct node *)struct node *insert_beg(struct node *)struct node *insert_end(struct node *)struct node *delete_beg(struct node *)struct node *delete_end(struct node *)struct node *delete_node(struct node *)struct node *delete_list(struct node *)int main(int optionclrscr()do printf("\ \ *****main menu *****")printf("\ create list")printf("\ display the list")printf("\ add node at the beginning")printf("\ add node at the end")printf("\ delete node from the beginning")printf("\ delete node from the end")printf("\ delete given node")printf("\ delete the entire list")printf("\ exit")printf("\ \ enter your option ")
24,424
data structures using scanf("% "&option)switch(optioncase start create_ll(start)printf("\ circular doubly linked list created")breakcase start display(start)breakcase start insert_beg(start)breakcase start insert_end(start)breakcase start delete_beg(start)breakcase start delete_end(start)breakcase start delete_node(start)breakcase start delete_list(start)printf("\ circular doubly linked list deleted")break}while(option ! )getch()return struct node *create_ll(struct node *startstruct node *new_node*ptrint numprintf("\ enter - to end")printf("\ enter the data ")scanf("% "&num)while(num !- if(start =nullnew_node (struct node*)malloc(sizeof(struct node))new_node -prev nullnew_node -data numnew_node -next startstart new_nodeelse new_node (struct node*)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -next !startptr ptr -nextnew_node -prev ptrptr -next new_nodenew_node -next startstart -prev new_nodeprintf("\ enter the data ")scanf("% "&num)
24,425
return startstruct node *display(struct node *startstruct node *ptrptr startwhile(ptr -next !startprintf("\ % "ptr -data)ptr ptr -nextprintf("\ % "ptr -data)return startstruct node *insert_beg(struct node *startstruct node *new_node*ptrint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node-data numptr startwhile(ptr -next !startptr ptr -nextnew_node -prev ptrptr -next new_nodenew_node -next startstart -prev new_nodestart new_nodereturn startstruct node *insert_end(struct node *startstruct node *ptr*new_nodeint numprintf("\ enter the data ")scanf("% "&num)new_node (struct node *)malloc(sizeof(struct node))new_node -data numptr startwhile(ptr -next !startptr ptr -nextptr -next new_nodenew_node -prev ptrnew_node -next startstart-prev new_nodereturn startstruct node *delete_beg(struct node *startstruct node *ptrptr startwhile(ptr -next !startptr ptr -nextptr -next start -nexttemp startstart=start->nextstart->prev=ptrfree(temp)return start
24,426
data structures using struct node *delete_end(struct node *startstruct node *ptrptr=startwhile(ptr -next !startptr ptr -nextptr -prev -next startstart -prev ptr -prevfree(ptr)return startstruct node *delete_node(struct node *startstruct node *ptrint valprintf("\ enter the value of the node which has to be deleted ")scanf("% "&val)ptr startif(ptr -data =valstart delete_beg(start)return startelse while(ptr -data !valptr ptr -nextptr -prev -next ptr -nextptr -next -prev ptr -prevfree(ptr)return startstruct node *delete_list(struct node *startstruct node *ptrptr startwhile(ptr -next !startstart delete_end(start)free(start)return startoutput *****main menu **** create list display the list delete the entire list exit enter your option enter - to end enter the data enter the data enter the data enter the data- circular doubly linked list created enter your option circular doubly linked list deleted enter your option
24,427
header linked lists header linked list is special type of linked list which contains header node at the beginning of the list soin header linked liststart will not point to the first node of the list but start will contain the address of the header node the following are the two variants of header linked listgrounded header linked list which stores null in the next field of the last node circular header linked list which stores the address of the header node in the next field of the last node herethe header node will denote the end of the list look at fig which shows both the types of header linked lists header node start header node start figure header linked list as in other linked listsif start nullthen this denotes an empty header linked list let us see how grounded header linked list is stored in the memory in grounded header start linked lista node has two fieldsdata and next the data field will store the information part and the next field will store the address of the node in sequence consider fig note that start stores the address of the header node the shaded row denotes header node the next field of the header - node stores the address of the first node of the list this node figure memory representation of stores the corresponding next field stores the address of the header linked list next nodewhich is sowe will look at address to fetch next data the next data item hencewe see that the first node can be accessed by writing first_node start -next and not by writing start first_ start node this is because start points to the header node and the header node points to the first node of the header linked list let us now see how circular header linked list is stored in the memory look at fig note that the last node in this case stores the address of the header node (instead of - figure memory representation of hencewe see that the first node can be circular header linked list accessed by writing first_node start -next and not writing start first_node this step set ptr start -next is because start points to the header node and step repeat steps and while ptr !start the header node points to the first node of the step apply process to ptr -data header linked list step set ptr ptr -next let us quickly look at figs and [end of loopstep exit that show the algorithms to traverse circular header linked listinsert new node in itand figure algorithm to traverse circular header linked list delete an existing node from it data next
24,428
data structures using step if avail null write overflow go to step [end of ifstep set new_node avail step set avail avail -next step set ptr start -next step set new_node -data val step repeat step while ptr -data !num step set ptr ptr -next [end of loopstep new_node -next ptr -next step set ptr -next new_node step exit figure step set ptr start->next step repeat steps and while ptr -data !val step set preptr ptr step set ptr ptr -next [end of loopstep set preptr -next ptr -next step free ptr step exit algorithm to insert new node in figure algorithm to delete node from circular circular header linked list header linked list after discussing linked lists in such detailthese algorithms are self-explanatory there is actually just one small difference between these algorithms and the algorithms that we have discussed earlier like we have header list and circular header listwe also have two-way (doublyheader list and circular two-way (doublyheader list the algorithms to perform all the basic operations will be exactly the same except that the first node will be accessed by writing start -next instead of start programming example write program to implement header linked list #include #include #include struct node int datastruct node *next}struct node *start nullstruct node *create_hll(struct node *)struct node *display(struct node *)int main(int optionclrscr()do printf("\ \ *****main menu *****")printf("\ create list")printf("\ display the list")printf("\ exit")printf("\ enter your option ")scanf("% "&option)switch(optioncase start create_hll(start)printf("\ header linked list created")break
24,429
case start display(start)break}while(option != )getch()return struct node *create_hll(struct node *startstruct node *new_node*ptrint numprintf("\ enter - to end")printf("\ enter the data ")scanf("% "&num)while(num!=- new_node (struct node*)malloc(sizeof(struct node))new_node->data=numnew_node->next=nullif(start==nullstart (struct node*)malloc(sizeof(struct node))start->next=new_nodeelse ptr=startwhile(ptr->next!=nullptr=ptr->nextptr->next=new_nodeprintf("\ enter the data ")scanf("% "&num)return startstruct node *display(struct node *startstruct node *ptrptr=startwhile(ptr!=nullprintf("\ % "ptr->data)ptr ptr->nextreturn startoutput *****main menu **** create list display the list exit enter your option enter - to end enter the data enter the data enter the data enter the data- header linked list created enter your option
24,430
data structures using multi-linked lists in multi-linked listeach node can have number of pointers to other nodes doubly linked list is special case of multi-linked lists howeverunlike doubly linked listsnodes in multilinked list may or may not have inverses for each pointer we can differentiate doubly linked list from multi-linked list in two ways(aa doubly linked list has exactly two pointers one pointer points to the previous node and the other points to the next node but node in the multi-linked list can have any number of pointers (bin doubly linked listpointers are exact inverses of each otheri for every pointer which points to previous node there is pointer which points to the next node this is not true for multi-linked list multi-linked lists are generally used to organize multiple orders of one set of elements for exampleif we have linked list that stores name and marks obtained by students in classthen we can organize the nodes of the list in two ways(iorganize the nodes alphabetically (according to the name(iiorganize the nodes according to decreasing order of marks so that the information of student who got highest marks comes before other students figure shows multi-linked list in which studentsnodes are organized by both the aforementioned ways advik goransh dev saisha null zara null figure multi-linked list that stores names alphabetically as well as according to decreasing order of marks new node can be inserted in multi-linked list in the same way as it is done for doubly linked list note in multi-linked listswe can have inverses of each pointer as in doubly linked list but for that we must have four pointers in single node figure sparse matrix multi-linked lists are also used to store sparse matrices in we have read about sparse matrices such matrices have very few non-zero values stored and most of the entries are zero sparse matrices are very common in engineering applications if we use normal array to store such matriceswe will end up wasting lot of space thereforea better solution is to represent these matrices using multi-linked lists the sparse matrix shown in fig can be represented using linked list for every row and column since value is in exactly one row and one columnit will appear in both lists exactly once node in the multi-linked will have four parts first stores the datasecond stores pointer to the next node in the rowthird stores pointer to the next node in the columnand the fourth stores the coordinates or the row and column number in which the data appears in
24,431
the matrix howeveras in case of doubly linked listswe can also have corresponding inverse pointer for every pointer in the multi-linked list representation of sparse matrix note when non-zero value in the sparse matrix is set to zerothe corresponding node in the multi-linked list must be deleted ( null null null co-ordinate ( data value ( null null next in column ( null null next in row figure multi-linked representation of sparse matrix shown in fig applications of linked lists linked lists can be used to represent polynomials and the different operations that can be performed on them in this sectionwe will see how polynomials are represented in the memory using linked lists polynomial representation let us see how polynomial is represented in the memory using linked list consider polynomial every individual term in polynomial consists of two partsa coefficient and power here and are the coefficients of the terms that have and as their powers respectively every term of polynomial can be represented as node of the linked list figure shows the linked representation of the terms of the above polynomial figure linked representation of polynomial now that we know how polynomials are represented using nodes of linked listlet us write program to perform operations on polynomials
24,432
data structures using programming example write program to store polynomial using linked list alsoperform addition and subtraction on two polynomials #include #include #include struct node int numint coeffstruct node *next}struct node *start nullstruct node *start nullstruct node *start nullstruct node *start nullstruct node *last nullstruct node *create_poly(struct node *)struct node *display_poly(struct node *)struct node *add_poly(struct node *struct node *struct node *)struct node *sub_poly(struct node *struct node *struct node *)struct node *add_node(struct node *intint)int main(int optionclrscr()do printf("\ ******main menu *******")printf("\ enter the first polynomial")printf("\ display the first polynomial")printf("\ enter the second polynomial")printf("\ display the second polynomial")printf("\ add the polynomials")printf("\ display the result")printf("\ subtract the polynomials")printf("\ display the result")printf("\ exit")printf("\ \ enter your option ")scanf("% "&option)switch(optioncase start create_poly(start )breakcase start display_poly(start )breakcase start create_poly(start )breakcase start display_poly(start )breakcase start add_poly(start start start )breakcase start display_poly(start )breakcase start sub_poly(start start start )breakcase start display_poly(start )
24,433
break}while(option!= )getch()return struct node *create_poly(struct node *startstruct node *new_node*ptrint ncprintf("\ enter the number ")scanf("% "& )printf("\ enter its coefficient ")scanf("% "& )while( !- if(start==nullnew_node (struct node *)malloc(sizeof(struct node))new_node -num nnew_node -coeff cnew_node -next nullstart new_nodeelse ptr startwhile(ptr -next !nullptr ptr -nextnew_node (struct node *)malloc(sizeof(struct node))new_node -num nnew_node -coeff cnew_node -next nullptr -next new_nodeprintf("\ enter the number ")scanf("% "& )if( =- breakprintf("\ enter its coefficient ")scanf("% "& )return startstruct node *display_poly(struct node *startstruct node *ptrptr startwhile(ptr !nullprintf("\ % % \ "ptr -numptr -coeff)ptr ptr -nextreturn startstruct node *add_poly(struct node *start struct node *start struct node *start struct node *ptr *ptr int sum_numc
24,434
data structures using ptr start ptr start while(ptr !null &ptr !nullif(ptr -coeff =ptr -coeffsum_num ptr -num ptr -numstart add_node(start sum_numptr -coeff)ptr ptr -nextptr ptr -nextelse if(ptr -coeff ptr -coeffstart add_node(start ptr -numptr -coeff)ptr ptr -nextelse if(ptr -coeff coeffstart add_node(start ptr -numptr -coeff)ptr ptr -nextif(ptr =nullwhile(ptr !nullstart add_node(start ptr -numptr -coeff)ptr ptr -nextif(ptr =nullwhile(ptr !nullstart add_node(start ptr -numptr -coeff)ptr ptr -nextreturn start struct node *sub_poly(struct node *start struct node *start struct node *start struct node *ptr *ptr int sub_numcptr start ptr start do if(ptr -coeff =ptr -coeffsub_num ptr -num ptr -numstart add_node(start sub_numptr -coeff)ptr ptr -nextptr ptr -nextelse if(ptr -coeff ptr -coeffstart add_node(start ptr -numptr -coeff)ptr ptr -nextelse if(ptr -coeff coeff
24,435
start add_node(start ptr -numptr -coeff)ptr ptr -next}while(ptr !null |ptr !null)if(ptr =nullwhile(ptr !nullstart add_node(start ptr -numptr -coeff)ptr ptr -nextif(ptr =nullwhile(ptr !nullstart add_node(start ptr -numptr -coeff)ptr ptr -nextreturn start struct node *add_node(struct node *startint nint cstruct node *ptr*new_nodeif(start =nullnew_node (struct node *)malloc(sizeof(struct node))new_node -num nnew_node -coeff cnew_node -next nullstart new_nodeelse ptr startwhile(ptr -next !nullptr ptr -nextnew_node (struct node *)malloc(sizeof(struct node))new_node -num nnew_node -coeff cnew_node -next nullptr -next new_nodereturn startoutput ******main menu ****** enter the first polynomial display the first polynomial exit enter your option enter the number enter its coefficient enter the number enter its coefficient enter the number - enter your option enter your option
24,436
data structures using points to remember linked list is linear collection of data elements called as nodes in which linear representation is given by links from one node to another linked list is data structure which can be used to implement other data structures such as stacksqueuesand their variations before we insert new node in linked listswe need to check for overflow conditionwhich occurs when no free memory cell is present in the system before we delete node from linked listwe must first check for underflow condition which occurs when we try to delete node from linked list that is empty when we delete node from linked listwe have to actually free the memory occupied by that node the memory is returned back to the free pool so that it can be used to store other programs and data in circular linked listthe last node contains pointer to the first node of the list while traversing circular linked listwe can begin at any node and traverse the list in any direction forward or backward until we reach the same node where we had started doubly linked list or two-way linked list is linked list which contains pointer to the next as well as the previous node in the sequence thereforeit consists of three parts--dataa pointer to the next nodeand pointer to the previous node the prev field of the first node and the next field of the last node contain null this enables to traverse the list in the backward direction as well thusa doubly linked list calls for more space per node and more expensive basic operations howevera doubly linked list provides the ease to manipulate the elements of the list as it maintains pointers to nodes in both the directions (forward and backwardthe main advantage of using doubly linked list is that it makes search operation twice as efficient circular doubly linked list or circular two-way linked list is more complex type of linked list which contains pointer to the next as well as previous node in the sequence the difference between doubly linked and circular doubly linked list is that the circular doubly linked list does not contain null in the previous field of the first node and the next field of the last node ratherthe next field of the last node stores the address of the first node of the list similarlythe previous field of the first field stores the address of the last node header linked list is special type of linked list which contains header node at the beginning of the list soin header linked list start will not point to the first node of the list but start will contain the address of the header node multi-linked lists are generally used to organize multiple orders of one set of elements in multilinked listeach node can have number of pointers to other nodes exercises review questions make comparison between linked list and linear array which one will you prefer to use and when why is doubly linked list more useful than singly linked list give the advantages and uses of circular linked list specify the use of header node in header linked list give the linked representation of the following polynomial xy explain the difference between circular linked list and singly linked list form linked list to store studentsdetails use the linked list of the above question to insert the record of new student in the list delete the record of student with specified roll number from the list maintained in question given linked list that contains english alphabet the characters may be in upper case or in lower case create two linked lists--one which stores upper case characters and the other that stores lower case characters
24,437
create linked list which stores names of the employees then sort these names and re-display the contents of the linked list programming exercises write program that removes all nodes that have duplicate information write program to print the total number of occurrences of given item in the linked list write program to multiply every element of the linked list with write program to print the number of non-zero elements in the list write program that prints whether the given linked list is sorted (in ascending orderor not write program that copies circular linked list write program to merge two linked lists write program to sort the values stored in doubly circular linked list write program to merge two sorted linked lists the resultant list must also be sorted write program to delete the firstlastand middle node of header linked list write program to create linked list from an already given list the new linked list must contain every alternate element of the existing linked list write program to concatenate two doubly linked lists write program to delete the first element of doubly linked list add this node as the last node of the list write program to (adelete the first occurrence of given character in linked list (bdelete the last occurrence of given character (cdelete all the occurrences of given character write program to reverse linked list using recursion write program to input an digit number nowbreak this number into its individual digits and then store every single digit in separate node thereby forming linked list for exampleif you enter then there will nodes in the list containing nodes with values write program to add the values of the nodes of linked list and then calculate the mean write program that prints minimum and maximum values in linked list that stores integer values write program to interchange the value of the first element with the last elementsecond element with second last elementso on and so forth of doubly linked list write program to make the first element of singly linked list as the last element of the list write program to count the number of occurrences of given value in linked list write program that adds to the values stored in the nodes of doubly linked list write program to form linked list of floating point numbers display the sum and mean of these numbers write program to delete the kth node from linked list write program to perform deletions in all the cases of circular header linked list write program to multiply polynomial with given number write program to count the number of non-zero values in circular linked list write program to create linked list which stores the details of employees in department read and print the information stored in the list use the linked list of question so that it displays the record of given employee only use the linked list of question and insert information about new employee use the linked list of question and delete information about an existing employee write program to move middle node of doubly link list to the top of the list write program to create singly linked list and reverse the list by interchanging the links and not the data write program that prints the nth element from the end of linked list in single pass write program that creates singly linked list use function issorted that returns if the list is sorted and otherwise write program to interchange the kth and the ( + )th node of circular doubly linked list write program to create header linked list
24,438
data structures using write program to delete node from circular header linked list write program to delete all nodes from header linked list that has negative values in its data part multiple-choice questions linked list is (arandom access structure (bsequential access structure (cboth (dnone of these an array is (arandom access structure (bsequential access structure (cboth (dnone of these linked list is used to implement data structures like (astacks (bqueues (ctrees (dall of these which type of linked list contains pointer to the next as well as the previous node in the sequence(asingly linked list (bcircular linked list (cdoubly linked list (dall of these which type of linked list does not store null in next field(asingly linked list (bcircular linked list (cdoubly linked list (dall of these which type of linked list stores the address of the header node in the next field of the last node(asingly linked list (bcircular linked list (cdoubly linked list (dcircular header linked list which type of linked list can have four pointers per node(acircular doubly linked list (bmulti-linked list (cheader linked list (ddoubly linked list true or false linked list is linear collection of data elements linked list can grow and shrink during run time node in linked list can point to only one node at time node in singly linked list can reference the previous node linked list can store only integer values linked list is random access structure deleting node from doubly linked list is easier than deleting it from singly linked list every node in linked list contains an integer part and pointer start stores the address of the first node in the list underflow is condition that occurs when we try to delete node from linked list that is empty fill in the blanks is used to store the address of the first free memory location the complexity to insert node at the beginning of the linked list is the complexity to delete node from the end of the linked list is inserting node at the beginning of the doubly linked list needs to modify pointers inserting node in the middle of the singly linked list needs to modify pointers inserting node at the end of the circular linked list needs to modify pointers inserting node at the beginning of the circular doubly linked list needs to modify pointers deleting node from the beginning of the singly linked list needs to modify pointers deleting node from the middle of the doubly linked list needs to modify pointers deleting node from the end of circular linked list needs to modify pointers each element in linked list is known as first node in the linked list is called the data elements in linked list are known as overflow occurs when in circular linked listthe last node contains pointer to the node of the list
24,439
stacks learning objective stack is an important data structure which is extensively used in computer applications in this we will study about the important features of stacks to understand how and why they organize the data so uniquely the will also illustrate the implementation of stacks by using both arrays as well as linked lists finallythe will discuss in detail some of the very useful areas where stacks are primarily used introduction stack is an important data structure which stores its elements in an ordered manner we will explain the concept of stacks using an analogy you must have seen pile of plates where one plate is placed on top of another as shown in fig nowwhen you want to remove plateyou remove the topmost plate first henceyou can add and remove an element ( plateonly at/from one position which is the topmost position stack is linear data structure which uses the same principlei the elements in stack are added and removed only from one endwhich is called the top hencea stack is called lifo (last-in-first-outdata the topmost another plate structureas the element that was inserted last is the first one to plate will will be be removed added on top be taken out first of this now the question is where do we need stacks in computer plate sciencethe answer is in function calls consider an examplewhere we are executing function in the course of its executionfunction calls another function function in turn calls another function cwhich calls function figure stack of plates
24,440
data structures using function function function function when calls ba is pushed on top of the system stack when the execution of is completethe system control will remove from the stack and continue with its execution when calls dc is pushed on top of the system stack when the execution of is completethe system control will remove from the stack and continue with its execution when calls cb is pushed on top of the system stack when the execution of is completethe system control will remove from the stack and continue with its execution function function when calls ed is pushed on top of the system stack when the execution of is completethe system control will remove from the stack and continue with its execution function function function function figure system stack in the case of function calls function function function when has executedd will be removed for execution function function function when has executedb will be removed for execution function when has executedc will be removed for execution function when has executeda will be removed for execution function function in order to keep track of the returning point of each active functiona special stack called system stack or call stack is used whenever function calls another functionthe calling function is pushed onto the top of the stack this is because after the called function gets executedthe control is passed back to the calling function look at fig which shows this concept now when function is executedfunction will be removed from the top of the stack and executed once function gets completely executedfunction will be removed from the stack for execution the whole procedure will be repeated until all the functions get executed let us look at the stack after each function is executed this is shown in fig the system stack ensures proper execution order of functions thereforestacks are frequently used in situations where the order of processing is very importantespecially when the processing needs to be postponed until other conditions are fulfilled stacks can be implemented using either arrays or linked lists in the following sectionswe will discuss both array and linked list implementation of stacks array representation of stacks in the computer' memorystacks can be represented as linear array every stack has variable called top associated with itwhich is used to store the address of the topmost element of the stack it is this position where the element will be added to or deleted from there is another variable called maxwhich is used to store the maximum number of elements that the stack can hold if top nullthen it indicates that the stack is empty and if top max- then the stack is full (you must be wondering why we have written max- it is because array indices start from look at fig figure system stack when called function returns to the calling function ab abc abcd abcde top figure stack the stack in fig shows that top so insertions and deletions will be done at this position in the above stackfive more elements can still be stored
24,441
operations on stack stack supports three basic operationspushpopand peek the push operation adds an element to the top of the stack and the pop operation removes the element from the top of the stack the peek operation returns the value of the topmost element of the stack push operation the push operation is used to insert an element into the stack the new element is added at the topmost position of the stack howeverbefore inserting the valuewe must first check if top=max- because if that is the casethen the stack is full and no more insertions can be done if an attempt is made to insert value in stack that is already fullan overflow message is printed consider the stack given in fig top figure stack to insert an element with value we first check if top=max- if the condition is falsethen we increment the value of top and store the new element at the position given by stack[topthusthe updated stack becomes as shown in fig top figure stack after insertion figure shows the algorithm to insert an element in stack in step we first check for the overflow condition in step top is incremented so that it points to the next location in the array in step the value is stored in the stack at the location pointed by top step if top max- print "overflowgoto step [end of ifstep set top top step set stack[topvalue step end pop operation the pop operation is used to delete the topmost element from the stack howeverbefore deleting the valuewe must first check if figure algorithm to insert an element in stack top=null because if that is the casethen it means the stack is empty and no more deletions can be done if an attempt is made to delete value from stack that is already emptyan underflow message is printed consider the stack given in fig top figure stack to delete the topmost elementwe first check if top=null if the condition is falsethen we decrement the value pointed by top thusthe updated stack becomes as shown in fig step if top null print "underflowgoto step [end of ifstep set val stack[topstep set top top step end figure algorithm to delete an element from stack top figure stack after deletion figure shows the algorithm to delete an element from stack in step we first check for the underflow condition in step the value of the location in the stack pointed by top is stored in val in step top is decremented
24,442
data structures using peek operation peek is an operation that returns the value of the topmost element of the stack without deleting it from the stack the algorithm for peek operation is given in fig howeverthe peek operation first checks if the stack is emptyi if top nullthen an appropriate message is printedelse the value is returned consider the stack given in fig step if top null print "stack is emptygoto step step return stack[topstep end figure algorithm for peek operation top figure stack herethe peek operation will return as it is the value of the topmost element of the stack programming example write program to perform pushpopand peek operations on stack #include #include #include #define max /altering this value changes size of stack created int st[max]top=- void push(int st[]int val)int pop(int st[])int peek(int st[])void display(int st[])int main(int argcchar *argv[]int valoptiondo printf("\ *****main menu*****")printf("\ push")printf("\ pop")printf("\ peek")printf("\ display")printf("\ exit")printf("\ enter your option")scanf("% "&option)switch(optioncase printf("\ enter the number to be pushed on stack")scanf("% "&val)push(stval)breakcase val pop(st)if(val !- printf("\ the value deleted from stack is% "val)breakcase val peek(st)if(val !-
24,443
printf("\ the value stored at top of stack is% "val)breakcase display(st)break}while(option ! )return void push(int st[]int valif(top =max- printf("\ stack overflow")else top++st[topvalint pop(int st[]int valif(top =- printf("\ stack underflow")return - else val st[top]top--return valvoid display(int st[]int iif(top =- printf("\ stack is empty")else for( =top; >= ; --printf("\ % ",st[ ])printf("\ ")/added for formatting purposes int peek(int st[]if(top =- printf("\ stack is empty")return - else return (st[top])
24,444
data structures using output *****main menu**** push pop peek display exit enter your option enter the number to be pushed on stack linked representation of stacks we have seen how stack is created using an array this technique of creating stack is easybut the drawback is that the array must be declared to have some fixed size in case the stack is very small one or its maximum size is known in advancethen the array implementation of the stack gives an efficient implementation but if the array size cannot be determined in advancethen the other alternativei linked representationis used the storage requirement of linked representation of the stack with elements is ( )and the typical time requirement for the operations is ( in linked stackevery node has two parts--one that stores data and another that stores the address of the next node the start pointer of the linked list is used as top all insertions and deletions are done at the node pointed by top if top nullthen it indicates that the stack is empty the linked representation of stack is shown in fig top figure linked stack operations on linked stack linked stack supports all the three stack operationsthat ispushpopand peek push operation the push operation is used to insert an element into the stack the new element is added at the topmost position of the stack consider the linked stack shown in fig top figure linked stack to insert an element with value we first check if top=null if this is the casethen we allocate memory for new nodestore the value in its data part and null in its next part the new node will then be called top howeverif top!=nullthen we insert the new node at the beginning of the linked stack and name this new node as top thusthe updated stack becomes as shown in fig top figure linked stack after inserting new node figure shows the algorithm to push an element into linked stack in step memory is allocated for the new node in step the data part of the new node is initialized with the value to be stored in the node in step we check if the new node is the first node of the linked list this
24,445
step allocate memory for the new node and name it as new_node step set new_node -data val step if top null set new_node -next null set top new_node else set new_node -next top set top new_node [end of ifstep end is done by checking if top null in case the if statement evaluates to truethen null is stored in the next part of the node and the new node is called top howeverif the new node is not the first node in the listthen it is added before the first node of the list (that isthe top nodeand termed as top pop operation the pop operation is used to delete the topmost element from stack howeverbefore deleting the valuewe must first check if top=nullbecause if this is the casethen it means that the figure algorithm to insert an element in stack is empty and no more deletions can be done if an linked stack attempt is made to delete value from stack that is already emptyan underflow message is printed consider the stack shown in fig top figure linked stack in case top!=nullthen we will delete the node pointed by topand make top point to the second element of the linked stack thusthe updated stack becomes as shown in fig step if top null print "underflowgoto step [end of ifstep set ptr top step set top top -next step free ptr step end figure algorithm to delete an element from linked stack figure linked stack after deletion of the topmost element figure shows the algorithm to delete an element from stack in step we first check for the underflow condition in step we use pointer ptr that points to top in step top is made to point to the next node in sequence in step the memory occupied by ptr is given back to the free pool programming example top write program to implement linked stack ##include #include #include #include struct stack int datastruct stack *next}struct stack *top nullstruct stack *push(struct stack *int)struct stack *display(struct stack *)struct stack *pop(struct stack *)int peek(struct stack *)int main(int argcchar *argv[]int valoption
24,446
data structures using do printf("\ *****main menu*****")printf("\ push")printf("\ pop")printf("\ peek")printf("\ display")printf("\ exit")printf("\ enter your option")scanf("% "&option)switch(optioncase printf("\ enter the number to be pushed on stack")scanf("% "&val)top push(topval)breakcase top pop(top)breakcase val peek(top)if (val !- printf("\ the value at the top of stack is% "val)else printf("\ stack is empty")breakcase top display(top)break}while(option ! )return struct stack *push(struct stack *topint valstruct stack *ptrptr (struct stack*)malloc(sizeof(struct stack))ptr -data valif(top =nullptr -next nulltop ptrelse ptr -next toptop ptrreturn topstruct stack *display(struct stack *topstruct stack *ptrptr topif(top =nullprintf("\ stack is empty")else
24,447
while(ptr !nullprintf("\ % "ptr -data)ptr ptr -nextreturn topstruct stack *pop(struct stack *topstruct stack *ptrptr topif(top =nullprintf("\ stack underflow")else top top -nextprintf("\ the value being deleted is% "ptr -data)free(ptr)return topint peek(struct stack *topif(top==nullreturn - else return top ->dataoutput *****main menu**** push pop peek display exit enter your option enter the number to be pushed on stack multiple stacks while implementing stack using an arraywe had seen that the size of the array must be known in advance if the stack is allocated less spacethen frequent overflow conditions will be encountered to deal with this problemthe code will have to be modified to reallocate more space for the array in case we allocate large amount of space for the stackit may result in sheer wastage of memory thusthere lies trade-off between the frequency of overflows and the space allocated soa better solution to deal with this problem is to have multiple stacks or to have more than one stack in the same array of sufficient size figure illustrates this concept stack - - - - stack figure multiple stacks in fig an array stack[nis used to represent two stacksstack and stack the value of is such that the combined size of both the stacks will never exceed while operating on
24,448
data structures using these stacksit is important to note one thing--stack will grow from left to rightwhereas stack will grow from right to left at the same time extending this concept to multiple stacksa stack can also be used to represent number of stacks in the same array that isif we have stack[ ]then each stack will be allocated an equal amount of space bounded by indices [iand [ithis is shown in fig [ [ [ [ [ [ [ figure multiple stacks programing example write program to implement multiple stacks #include #include #define max int stack[max],topa=- ,topb=maxvoid pusha(int valif(topa==topb- printf("\ overflow")else topa+ stack[topavalint popa(int valif(topa==- printf("\ underflow")val - else val stack[topa]topa--return valvoid display_stacka(int iif(topa==- printf("\ stack is empty")else for( =topa; >= ; --printf("\ % ",stack[ ])void pushb(int valif(topb- ==topaprintf("\ overflow")else [ [ [
24,449
topb - stack[topbvalint popb(int valif(topb==maxprintf("\ underflow")val - else val stack[topb]topb++void display_stackb(int iif(topb==maxprintf("\ stack is empty")else for( =topb; <max; ++printf("\ % ",stack[ ])void main(int optionvalclrscr()do printf("\ *****menu*****")printf("\ push in stack ")printf("\ push in stack ")printf("\ pop from stack ")printf("\ pop from stack ")printf("\ display stack ")printf("\ display stack ")printf("\ exit")printf("\ enter your choice")scanf("% ",&option)switch(optioncase printf("\ enter the value to push on stack ")scanf("% ",&val)pusha(val)breakcase printf("\ enter the value to push on stack ")scanf("% ",&val)pushb(val)breakcase val=popa()if(val!=- printf("\ the value popped from stack % ",val)break
24,450
data structures using case val=popb()if(val!=- printf("\ the value popped from stack % ",val)breakcase printf("\ the contents of stack are \ ")display_stacka()breakcase printf("\ the contents of stack are \ ")display_stackb()break}while(option!= )getch()output *****main menu**** push in stack push in stack pop from stack pop from stack display stack display stack exit enter your choice enter the value to push on stack enter the value to push on stack enter your choice the content of stack are enter your choice underflow enter your choice applications of stacks in this section we will discuss typical problems where stacks can be easily applied for simple and efficient solution the topics that will be discussed in this section include the followingreversing list parentheses checker conversion of an infix expression into postfix expression evaluation of postfix expression conversion of an infix expression into prefix expression evaluation of prefix expression recursion tower of hanoi reversing list list of numbers can be reversed by reading each number from an array starting from the first index and pushing it on stack once all the numbers have been readthe numbers can be popped one at time and then stored in the array starting from the first index programming example write program to reverse list of given numbers #include
24,451
#include int stk[ ]int top=- int pop()void push(int)int main(int valniarr[ ]clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )printf("\ enter the elements of the array ")for( = ; < ; ++scanf("% "&arr[ ])for( = ; < ; ++push(arr[ ])for( = ; < ; ++val pop()arr[ivalprintf("\ the reversed array is ")for( = ; < ; ++printf("\ % "arr[ ])getche"()return void push(int valstk[++topvalint pop(return(stk[top--])output enter the number of elements in the array enter the elements of the array the reversed array is implementing parentheses checker stacks can be used to check the validity of parentheses in any algebraic expression for examplean algebraic expression is valid if for every open bracket there is corresponding closing bracket for examplethe expression ( +bis invalid but an expression { ( )is valid look at the program below which traverses an algebraic expression to check for its validity programming example write program to check nesting of parentheses using stack #include #include #include #define max int top - int stk[max]void push(char)
24,452
char pop()void main(char exp[max],tempint iflag= clrscr()printf("enter an expression ")gets(exp)for( = ; <strlen(exp); ++if(exp[ ]=='(|exp[ ]=='{|exp[ ]=='['push(exp[ ])if(exp[ ]==')|exp[ ]=='}|exp[ ]==']'if(top =- flag= else temp=pop()if(exp[ ]==')&(temp=='{|temp=='[')flag= if(exp[ ]=='}&(temp=='(|temp=='[')flag= if(exp[ ]==']&(temp=='(|temp=='{')flag= if(top>= flag= if(flag== printf("\ valid expression")else printf("\ invalid expression")void push(char cif(top =(max- )printf("stack overflow\ ")else top=top+ stk[topcchar pop(if(top =- printf("\ stack underflow")else return(stk[top--])output enter an expression ( ( )valid expression evaluation of arithmetic expressions polish notations infixpostfixand prefix notations are three different but equivalent notations of writing algebraic expressions but before learning about prefix and postfix notationslet us first see what an infix notation is we all are familiar with the infix notation of writing algebraic expressions
24,453
while writing an arithmetic expression using infix notationthe operator is placed in between the operands for examplea+bhereplus operator is placed between the two operands and although it is easy for us to write expressions using infix notationcomputers find it difficult to parse as the computer needs lot of information to evaluate the expression information is needed about operator precedence and associativity rulesand brackets which override these rules socomputers work more efficiently with expressions written using prefix and postfix notations postfix notation was developed by jan lukasiewicz who was polish logicianmathematicianand philosopher his aim was to develop parenthesis-free prefix notation (also known as polish notationand postfix notationwhich is better known as reverse polish notation or rpn in postfix notationas the name suggeststhe operator is placed after the operands for exampleif an expression is written as + in infix notationthe same expression can be written as abin postfix notation the order of evaluation of postfix expression is always from left to right even brackets cannot alter the order of evaluation the expression ( bc can be written as[ab+]* ab+cin the postfix notation postfix operation does not even follow the rules of operator precedence the operator which occurs first in the expression is operated first on the operands for examplegiven postfix notation ab+cwhile evaluationaddition will be performed prior to multiplication ( ( - ( +dthus we see that in postfix notationoperators are [ab-[cd+applied to the operands that are immediately left to them ab-cd+in the exampleab+ *is applied on and bthen is ( ( ( ( eapplied on the result of addition and [ab+[cd+[de*[ab+cd+/[de*although prefix notation is also evaluated from left to ab+cd+/de*rightthe only difference between postfix notation and prefix notation is that in prefix notationthe operator is placed before the operands for exampleif + is an expression in infix notationthen the corresponding expression in prefix notation is given by +ab while evaluating prefix expressionthe operators are applied to the operands that are present immediately on the right of the operator like postfixprefix expressions also do not follow the rules of operator precedence and associativityand even brackets cannot alter the order of evaluation example convert the following infix expressions into postfix expressions solution example convert the following infix expressions into prefix expressions solution ( ( bc (+ab)* *+abc ( ( - ( + [-ab[+cd*-ab+cd ( ( bc dd [+ab[+cd[*de[/+ab+cd[*de-/+ab+cd*de conversion of an infix expression into postfix expression let be an algebraic expression written in infix notation may contain parenthesesoperandsand operators for simplicity of the algorithm we will use only +-*/operators the precedence of these operators can be given as followshigher priority */lower priority +no doubtthe order of evaluation of these operators can be changed by making use of parentheses for exampleif we have an expression cthen first will be done and the result will be added to but the same expression if written as( bcwill evaluate first and then the result will be multiplied with
24,454
data structures using the algorithm given below transforms an infix expression into postfix expressionas shown in fig the algorithm accepts an infix expression that may contain operatorsoperandsand parentheses for simplicitywe assume that the infix operation contains only modulus (%)multiplication (*)division (/)addition (+)and subtraction (--operators and that operators with same precedence are performed from left-to-right the algorithm uses stack to temporarily hold operators the postfix expression is obtained from left-to-right using the operands from the infix expression and the operators which are removed from the stack the first step in this algorithm is to push left parenthesis on the stack and to add corresponding right parenthesis at the end of the infix expression the algorithm is repeated until the stack is empty step add ")to the end of the infix expression step push "(on to the stack step repeat until each character in the infix notation is scanned if "(is encounteredpush it on the stack if an operand (whether digit or characteris encounteredadd it to the postfix expression if ")is encounteredthen repeatedly pop from stack and add it to the postfix expression until "(is encountered discard the "(that isremove the "(from stack and do not add it to the postfix expression if an operator is encounteredthen repeatedly pop from stack and add each operator (popped from the stackto the postfix expression which has the same precedence or higher precedence than push the operator to the stack [end of ifstep repeatedly pop from the stack and add it to the postfix expression until the stack is empty step exit figure algorithm to convert an infix notation to postfix notation solution infix character scanned stack postfix expression abc/def*% /+ *example convert the following infix expression into postfix expression using the algorithm given in fig (aa ( ( fg) (ba ( ( fg)hprogramming example write program to convert an infix expression into its equivalent postfix notation #include #include #include #include #define max char st[max]int top=- void push(char st[]char)char pop(char st[])
24,455
void infixtopostfix(char source[]char target[])int getpriority(char)int main(char infix[ ]postfix[ ]clrscr()printf("\ enter any infix expression ")gets(infix)strcpy(postfix"")infixtopostfix(infixpostfix)printf("\ the corresponding postfix expression is ")puts(postfix)getch()return void infixtopostfix(char source[]char target[]int = = char tempstrcpy(target"")while(source[ ]!='\ 'if(source[ ]=='('push(stsource[ ]) ++else if(source[ =')'while((top!=- &(st[top]!='(')target[jpop(st) ++if(top==- printf("\ incorrect expression")exit( )temp pop(st);//remove left parenthesis ++else if(isdigit(source[ ]|isalpha(source[ ])target[jsource[ ] ++ ++else if (source[ ='+|source[ ='-|source[ ='*|source[ ='/|source[ ='%'while(top!=- &(st[top]!'('&(getpriority(st[top]getpriority(source[ ]))target[jpop(st) ++push(stsource[ ]) ++else
24,456
data structures using printf("\ incorrect element in expression")exit( )while((top!=- &(st[top]!='(')target[jpop(st) ++target[ ]='\ 'int getpriority(char opif(op=='/|op ='*|op=='%'return else if(op=='+|op=='-'return void push(char st[]char valif(top==max- printf("\ stack overflow")else top++st[top]=valchar pop(char st[]char val='if(top==- printf("\ stack underflow")else val=st[top]top--return valoutput enter any infix expression + - * the corresponding postfix expression is ab+cd*evaluation of postfix expression the ease of evaluation acts as the driving force for computers to translate an infix notation into postfix notation that isgiven an algebraic expression written in infix notationthe computer first converts the expression into the equivalent postfix notation and then evaluates the postfix expression both these tasks--converting the infix notation into postfix notation and evaluating the postfix expression--make extensive use of stacks as the primary tool using stacksany postfix expression can be evaluated very easily every character of the postfix expression is scanned from left to right if the character encountered is an operandit is pushed on to the stack howeverif an operator is encounteredthen the top two values are popped from the stack and the operator is applied on these values the result is then pushed on to the stack let us look at fig which shows the algorithm to evaluate postfix expression
24,457
table evaluation of postfix expression character scanned figure stack algorithm to evaluate postfix expression let us now take an example that makes use of this algorithm consider the infix expression given as (( evaluate the expression the infix expression (( can be written as using postfix notation look at table which shows the procedure programming example write program to evaluate postfix expression #include #include #include #define max float st[max]int top=- void push(float st[]float val)float pop(float st[])float evaluatepostfixexp(char exp[])int main(float valchar exp[ ]clrscr()printf("\ enter any postfix expression ")gets(exp)val evaluatepostfixexp(exp)printf("\ value of the postfix expression "val)getch()return float evaluatepostfixexp(char exp[]int = float op op valuewhile(exp[ !'\ 'if(isdigit(exp[ ])
24,458
data structures using push(st(float)(exp[ ]-' '))else op pop(st)op pop(st)switch(exp[ ]case '+'value op op breakcase '-'value op op breakcase '/'value op op breakcase '*'value op op breakcase '%'value (int)op (int)op breakpush(stvalue) ++return(pop(st))void push(float st[]float valif(top==max- printf("\ stack overflow")else top++st[top]=valfloat pop(float st[]float val=- if(top==- printf("\ stack underflow")else val=st[top]top--return valoutput enter any postfix expression value of the postfix expression conversion of an infix expression into prefix expression there are two algorithms to convert an infix expression into its equivalent prefix expression the first algorithm is given in fig while the second algorithm is shown in fig
24,459
step scan each character in the infix expression for thisrepeat steps - until the end of infix expression step push the operator into the operator stackoperand into the operand stackand ignore all the left parentheses until right parenthesis is encountered step pop operand from operand stack step pop operand from operand stack step pop operator from operator stack step concatenate operator and operand step concatenate result with operand step push result into the operand stack step end figure algorithm to convert an infix expression into prefix expression step reverse the infix string note that while reversing the string you must interchange left and right parentheses step obtain the postfix expression of the infix expression obtained in step step reverse the postfix expression to get the prefix expression figure algorithm to convert an infix expression into prefix expression the corresponding prefix expression is obtained in the operand stack for examplegiven an infix expression ( ( lstep reverse the infix string note that while reversing the string you must interchange left and right parentheses ( ( astep obtain the corresponding postfix expression of the infix expression obtained as result of step the expression is( ( atherefore[ ( /)[( / [lka/-[cb/ - step reverse the postfix expression to get the prefix expression thereforethe prefix expression is / programming exam write program to convert an infix expression to prefix expression #include #include #include #include #define max char st[max]int top=- void reverse(char str[])void push(char st[]char)char pop(char st[])void infixtopostfix(char source[]char target[])int getpriority(char)char infix[ ]postfix[ ]temp[ ]int main(clrscr()printf("\\ enter any infix expression ")gets(infix)reverse(infix)strcpy(postfix"")infixtopostfix(temppostfix)printf("\ the corresponding postfix expression is ")puts(postfix)strcpy(temp,"")reverse(postfix)
24,460
data structures using printf("\ the prefix expression is \ ")puts(temp)getch()return void reverse(char str[]int leni= = len=strlen(str) =len- while( > if (str[ ='('temp[ ')'else if str[ =')'temp[ '('else temp[istr[ ] ++ --temp[ '\ 'void infixtopostfix(char source[]char target[]int = = char tempstrcpy(target"")while(source[ ]!'\ 'if(source[ ]=='('push(stsource[ ]) ++else if(source[ =')'while((top!=- &(st[top]!='(')target[jpop(st) ++if(top==- printf("\ incorrect expression")exit( )temp pop(st)//remove left parentheses ++else if(isdigit(source[ ]|isalpha(source[ ])target[jsource[ ] ++ ++else ifsource[ ='+|source[ ='-|source[ ='*|source[ ='/|source[ ='%'while(top!=- &(st[top]!'('&(getpriority(st[top]
24,461
getpriority(source[ ]))target[jpop(st) ++push(stsource[ ]) ++else printf("\ incorrect element in expression")exit( )while((top!=- &(st[top]!='(')target[jpop(st) ++target[ ]='\ 'int getprioritychar opif(op=='/|op ='*|op=='%'return else if(op=='+|op=='-'return void push(char st[]char valif(top==max- printf("\ stack overflow")else top++st[topvalchar pop(char st[]char val='if(top==- printf("\ stack underflow")else val=st[top]top--return valoutput enter any infix expression + - * the corresponding postfix expression is ab+cd*the prefix expression is -+ab*cd evaluation of prefix expression there are number of techniques for evaluating prefix expression the simplest way of evaluation of prefix expression is given in fig
24,462
data structures using for exampleconsider the prefix expression let us now apply the algorithm to evaluate this expression programming example write program to evaluate prefix expression figure algorithm for evaluation of prefix expression character scanned operand stack #include #include #include int stk[ ]int top=- int pop()void push(int)int main(char prefix[ ]int lenvaliopr opr resclrscr()printf("\ enter the prefix expression ")gets(prefix)len strlen(prefix)for( =len- ; >= ; --switch(get_type(prefix[ ]) case val prefix[ ' ' push(val) break case opr pop() opr pop() switch(prefix[ ] case '+'res opr opr breakcase '-'res opr opr breakcase '*'res opr opr breakcase '/'res opr opr breakpush(res)printf("\ result % "stk[ ])getche()return void push(int valstk[++topval
24,463
int pop(return(stk[top--])int get_type(char cif( ='+| ='-| ='*| ='/'return else return output enter the prefix expression +- result recursion in this section we are going to discuss recursion which is an implicit application of the stack adt recursive function is defined as function that calls itself to solve smaller version of its task until final call is made which does not require call to itself since recursive function repeatedly calls itselfit makes use of the system stack to temporarily store the return address and local variables of the calling function every recursive solution has two major cases they are base casein which the problem is simple enough to be solved directly without making any further calls to the same function recursive casein which first the problem at hand is divided into simpler sub-parts second the function calls itself but with sub-parts of the problem obtained in the first step thirdthe result is obtained by combining the solutions of simpler sub-parts thereforerecursion is defining large and complex problems in terms of smaller and more easily solvable problems in recursive functionsa complex problem is defined in terms of simpler problems and the simplest problem is given explicitly to understand recursive functionslet us take an example of calculating factorial of number to calculate !we multiply the number with factorial of the number that is less than that number in other wordsnn ( - )let us say we need to find the value of this can be written as !where ! therefore similarlywe can also write problem figure solution = = = = = = = = = = = = recursive factorial function expanding further we know the series of problems and solutions can be given as shown in fig now if you look at the problem carefullyyou can see that we can write recursive function to calculate the
24,464
data structures using factorial of number every recursive function must have base case and recursive case for the factorial functionbase case is when because if the result will be as programming tip every recursive function must recursive case of the factorial function will call itself but with have at least one base case smaller value of nthis case can be given as otherwisethe recursive function will generate an infinite sequence of callsthereby resulting in an error condition known as an infinite stack factorial(nn factorial ( - look at the following program which calculates the factorial of number recursively programming example write program to calculate the factorial of given number #include int fact(int)/function declaration int main(int numvalprintf("\ enter the number")scanf("% "&num)val fact(num)printf("\ factorial of % % "numval)return int fact(int nif( == return else return ( fact( - ))output enter the number factorial of from the above examplelet us analyse the steps of recursive program step specify the base case which will stop the function from making call to itself step check to see whether the current value being processed matches with the value of the base case if yesprocess and return the value step divide the problem into smaller or simpler sub-problems step call the function from each sub-problem step combine the results of the sub-problems step return the result of the entire problem greatest common divisor the greatest common divisor of two numbers (integersis the largest integer that divides both the numbers we can find the gcd of two numbers recursively by using the euclid' algorithm that states gcd (abbif divides gcd (ba mod )otherwise gcd can be implemented as recursive function because if does not divide athen we call the same function (gcdwith another set of parameters that are smaller than the original ones
24,465
here we assume that however if bthen interchange and in the formula given above working assume and gcd( rem gcd( rem gcd( rem return return return programming example write program to calculate the gcd of two numbers using recursive functions #include int gcd(intint)int main(int num num resprintf("\ enter the two numbers")scanf("% % "&num &num )res gcd(num num )printf("\ gcd of % and % % "num num res)return int gcd(int xint yint remrem %yif(rem== return yelse return (gcd(yrem))output enter the two numbers gcd of and finding exponents we can also find exponent of number using recursion to find xythe base case would be when = as we know that any number raised to the power is thereforethe general formula to find xy can be given as exp (xy if = exp ( - )otherwise working exp_rec( exp_rec( exp_rec( exp_rec( exp_rec( exp_rec( exp_rec( exp_rec( exp_rec( exp_rec( exp_rec(
24,466
data structures using exp_rec( exp_rec( programming example write program to calculate exp( ,yusing recursive functions #include int exp_rec(intint)int main(int num num resprintf("\ enter the two numbers")scanf("% % "&num &num )res exp_rec(num num )printf ("\ result % "res)return int exp_rec(int xint yif( == return else return ( exp_rec(xy- ))output enter the two numbers result the fibonacci series the fibonacci series can be given as that isthe third term of the series is the sum of the first and second terms similarlyfourth term is the sum of second and third termsand so on now we will design recursive solution to find the nth term of the fibonacci series the general formula to do so can be given as as per the formulafib( = and fib( so we have two base cases this is necessary because every problem is divided into two smaller problems fib ( if if fib ( fib( )otherwise programming example write program to print the fibonacci series using recursion #include int fibonacci(int)int main(int ni resprintf("enter the number of terms\ ")scanf("% ",& )printf("fibonacci series\ ")for( ni+res fibonacci( )
24,467
printf("% \ ",res)return int fibonacci(int nif = return else if = return else return fibonacci( - fibonacci( - )output enter the number of terms fibonacci series types of recursion recursion is technique that breaks problem into one or more sub-problems that are similar to the original problem any recursive function can be characterized based onwhether the function calls itself directly or indirectly (direct or indirect recursion)int func (int nwhether any operation is pending at each recursive call (tailif ( = recursive or not)and return nthe structure of the calling pattern (linear or tree-recursiveelse return (func ( - ))figure direct recursion int funcl (int nif ( = return nelse return func ( )int func (int xreturn func ( - )figure indirect recursion int fact(int nif ( = return else return ( fact( - ))figure non-tail recursion in this sectionwe will read about all these types of recursions direct recursion function is said to be directly recursiveif it explicitly calls itself for exampleconsider the code shown in fig herethe function func(calls itself for all positive values of nso it is said to be directly recursive function indirect recursion function is said to be indirectly recursive if it contains call to another function which ultimately calls it look at the functions given below these two functions are indirectly recursive as they both call each other (fig tail recursion recursive function is said to be tail recursive if no operations are pending to be performed when the recursive function returns to its caller when the called function returnsthe returned value is immediately returned from the calling function tail recursive functions are highly desirable because they are much more efficient to use as the amount of information that has to be stored on the system stack is independent of the number of recursive calls in fig the factorial function that we have written is nontail-recursive functionbecause there is pending operation of multiplication to be performed on return from each recursive call
24,468
whenever there is pending operation to be performedthe function becomes non-tail recursive in such non-tail recursive functioninformation about each pending operation must be storedso the amount of information directly depends on the number of calls howeverthe same factorial function can be written in tailrecursive manner as shown fig in the codefact function preserves the syntax of fact(nhere the recursion occurs in the fact function and not in fact function carefully observe that fact has no pending operation to be performed on return from recursive calls the value computed by figure tail recursion the recursive call is simply returned without any modification so in this casethe amount of information to be stored on the system stack is constant (only the values of and res need to be storedand is independent of the number of recursive calls int fact(nreturn fact ( )int fact (int nint resif ( = return reselse return fact ( - *res)converting recursive functions to tail recursive non-tail recursive function can be converted into tail-recursive function by using an auxiliary parameter as we did in case of the factorial function the auxiliary parameter is used to form the result when we use such parameterthe pending operation is incorporated into the auxiliary parameter so that the recursive call no longer has pending operation we generally use an auxiliary function while using the auxiliary parameter this is done to keep the syntax clean and to hide the fact that auxiliary parameters are needed linear and tree recursion int fibonacci(int numif(num =return else if (num = return else return (fibonacci(num fibonacci(num ))observe the series of function calls when the function returnsthe pending operations in turn calls the function fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( now we havefibonacci( fibonacci( fibonacci( fibonacci( fibonacci( fibonacci( figure tree recursion recursive functions can also be characterized depending on the way in which the recursion grows in linear fashion or forming tree structure (fig in simple wordsa recursive function is said to be linearly recursive when the pending operation (if anydoes not make another recursive call to the function for exampleobserve the last line of recursive factorial function the factorial function is linearly recursive as the pending operation involves only multiplication to be performed and does not involve another recursive call to fact on the contrarya recursive function is said to be tree recursive (or non-linearly recursiveif the pending operation makes another recursive call to the function for examplethe fibonacci function in which the pending operations recursively call the fib onacci function tower of hanoi the tower of hanoi is one of the main applications of recursion it says'if you can solve - casesthen you can easily solve the nth case
24,469
figure tower of hanoi figure move rings from to figure move ring from to figure move ring from to look at fig which shows three rings mounted on pole the problem is to move all these rings from pole to pole while maintaining the same order the main issue is that the smaller disk must always come above the larger disk we will be doing this using spare pole in our casea is the source polec is the destination poleand is the spare pole to transfer all the three rings from to cwe will first shift the upper two rings ( - ringsfrom the source pole to the spare pole we move the first two rings from pole to as shown in fig now that - rings have been removed from pole athe nth ring can be easily moved from the source pole (ato the destination pole (cfigure shows this step the final step is to move the - rings from the spare pole (bto the destination pole (cthis is shown in fig to summarizethe solution to our problem of moving rings from to using as spare can be given asbase caseif = move the ring from to using as spare recursive casemove rings from to using as spare move the one ring left on to using as spare move rings from to using as spare the following code implements the solution of the tower of hanoi problem #include int main(int nprintf("\ enter the number of rings")scanf("% "& )move( ,' '' '' ')return void move(int nchar sourcechar destchar spareif ( == printf("\ move from % to % ",source,dest)else move( - ,source,spare,dest)move( ,source,dest,spare)move( - ,spare,dest,source)let us look at the tower of hanoi problem in detail using the program given above figure on the next page explains the working of the program using onethen twoand finally three rings recursion versus iteration recursion is more of top-down approach to problem solving in which the original problem is divided into smaller sub-problems on the contraryiteration follows bottom-up approach that begins with what is known and then constructing the solution step by step recursion is an excellent way of solving complex problems especially when the problem can be defined in recursive terms for such problemsa recursive code can be written and modified in much simpler and clearer manner
24,470
data structures using howeverrecursive solutions are not always the best solutions in some casesrecursive programs may require substantial amount of run-time overhead thereforewhen implementing recursive solutionthere is trade-off involved between the time spent in constructing and maintaining the program and the cost incurred in running-time and memory space required for the execution of the program (step (step (step (if there is only one ringthen simply move the ring from source to the destination (step (step (step (if there are two ringsthen first move ring to the spare pole and then move ring from source to the destination finally move ring from spare to the destination (step (step (step (step (step (step (step (step (consider the working with three rings figure working of tower of hanoi with onetwoand three rings whenever recursive function is calledsome amount of overhead in the form of run time stack is always involved before jumping to the function with smaller parameterthe original parametersthe local variablesand the return address of the calling function are all stored on the system stack thereforewhile using recursion lot of time is needed to first push all the information on the stack when the function is called and then again in retrieving the information stored on the stack once the control passes back to the calling function to concludeone must use recursion only to find solution to problem for which no obvious iterative solution is known to summarize the concept of recursionlet us briefly discuss the pros and cons of recursion the advantages of using recursive program include the followingrecursive solutions often tend to be shorter and simpler than non-recursive ones code is clearer and easier to use recursion works similar to the original formula to solve problem recursion follows divide and conquer technique to solve problems in some (limitedinstancesrecursion may be more efficient
24,471
the drawbacks/disadvantages of using recursive program include the followingfor some programmers and readersrecursion is difficult concept recursion is implemented using system stack if the stack space on the system is limitedrecursion to deeper level will be difficult to implement aborting recursive program in midstream can be very slow process using recursive function takes more memory and time to execute as compared to its nonrecursive counterpart it is difficult to find bugsparticularly while using global variables the advantages of recursion pay off for the extra overhead involved in terms of time and space required points to remember stack is linear data structure in which elements are added and removed only from one endwhich is called the top hencea stack is called lifo (last-infirst-outdata structure as the element that is inserted last is the first one to be taken out in the computer' memorystacks can be implemented using either linked lists or single arrays the storage requirement of linked representation of stack with elements is (nand the typical time requirement for operations is ( infixprefixand postfix notations are three different but equivalent notations of writing algebraic expressions in postfix notationoperators are placed after the operandswhereas in prefix notationoperators are placed before the operands postfix notations are evaluated using stacks every character of the postfix expression is scanned from left to right if the character is an operandit is pushed onto the stack elseif it is an operatorthen the top two values are popped from the stack and the operator is applied on these values the result is then pushed onto the stack multiple stacks means to have more than one stack in the same array of sufficient size recursive function is defined as function that calls itself to solve smaller version of its task until final call is made which does not require call to itself they are implmented using system stack exercises review questions what do you understand by stack overflow and underflow differentiate between an array and stack how does stack implemented using linked list differ from stack implemented using an array differentiate between peek(and pop(functions why are parentheses not required in postfix/prefix expressions explain how stacks are used in non-recursive program what do you understand by multiple stackhow is it useful explain the terms infix expressionprefix expressionand postfix expression convert the following infix expressions to their postfix equivalents(aa (ba ( ( ( ( ( dd ( (( bd (( fg)(fa ( cd ef ( convert the following infix expressions to their postfix equivalents(aa (ba ( ( ( ( ( dd ( (( bd (( fg)(fa ( cd ef ( find the infix equivalents of the following postfix equivalents
24,472
data structures using (aa (babc give the infix expression of the following prefix expressions (aa (ba convert the expression given below into its corresponding postfix expression and then evaluate it also write program to evaluate postfix expression (( )/ write function that accepts two stacks copy the contents of first stack in the second stack note that the order of elements must be preserved (hintuse temporary stack draw the stack structure in each case when the following operations are performed on an empty stack (aadd abcdef (bdelete two letters (cadd (dadd (edelete four letters (fadd differentiate between an iterative function and recursive function which one will you prefer to use and in what circumstances explain the tower of hanoi problem programming exercises write program to implement stack using linked list write program to convert the expression " +binto "ab+ write program to convert the expression " +binto "+ab write program to implement stack that stores names of students in the class write program to input two stacks and compare their contents write program to compute (xy)where (xyf( -yy if ypsx and (xy if < write program to compute (nrwhere (nrcan be recursively defined asf(nrf( - rf( - - write program to compute lambda(nfor all positive values of where lambda(ncan be recursively defined aslambda(nlambda( / if > and lambda( if = write program to compute (mnwhere (mncan be recursively defined asf( , if = or >= >= and ( ,nf( - ,nf( - - )otherwise write program to reverse string using recursion multiple-choice questions stack is (alifo (bfifo (cfilo (dlilo which function places an element on the stack(apop((bpush((cpeek((disempty( disks piled up one above the other represent (astack (bqueue (clinked list (darray reverse polish notation is the other name of (ainfix expression (bprefix expression (cpostfix expression (dalgebraic expression true or false pop(is used to add an element on the top of the stack postfix operation does not follow the rules of operator precedence recursion follows divide-and-conquer technique to solve problems using recursive function takes more memory and time to execute recursion is more of bottom-up approach to problem solving an indirect recursive function if it contains call to another function which ultimately calls it the peek operation displays the topmost value and deletes it from the stack in stackthe element that was inserted last is the first one to be taken out underflow occurs when top max- the storage requirement of linked representation of the stack with elements is ( push operation on linked stack can be performed in (ntime overflow can never occur in case of multiple stacks fill in the blanks is used to convert an infix expression into postfix expression is used in non-recursive implementation of recursive algorithm the storage requirement of linked stack with elements is underflow takes when the order of evaluation of postfix expression is from whenever there is pending operation to be performedthe function becomes recursive function is said to be recursive if it explicitly calls itself
24,473
queues learning objective queue is an important data structure which is extensively used in computer applications in this we will study the operations that can be performed on queue the will also discuss the implementation of queue by using both arrays as well as linked lists the will illustrate different types of queues like multiple queuesdouble ended queuescircular queuesand priority queues the also lists some real-world applications of queues introduction let us explain the concept of queues using the analogies given below people moving on an escalator the people who got on the escalator first will be the first one to step out of it people waiting for bus the first person standing in the line will be the first one to get into the bus people standing outside the ticketing window of cinema hall the first person in the line will get the ticket first and thus will be the first one to move out of it luggage kept on conveyor belts the bag which was placed first will be the first to come out at the other end cars lined at toll bridge the first car to reach the bridge will be the first to leave in all these exampleswe see that the element at the first position is served first same is the case with queue data structure queue is fifo (first-infirst-outdata structure in which the element that is inserted first is the first one to be taken out the elements in queue are added at one end called the rear and removed from the other end called the front queues can be implemented by using either arrays or linked lists in this sectionwe will see how queues are implemented using each of these data structures
24,474
data structures using array representation of queues queues can be easily represented using linear arrays as stated earlierevery queue has front and rear variables that point to the position from where deletions and insertions can be donerespectively the array representation of queue is shown in fig operations on queues in fig front and rear suppose we figure queue want to add another element with value then rear would be incremented by and the value would be stored at the position pointed by rear the queue after addition would be as shown in figure queue after insertion of new element fig herefront and rear every time new element has to be addedwe repeat the same procedure if we want to delete an element from the figure queue after deletion of an element queuethen the value of front will be incremented deletions are done from only this end of the queue the queue after deletion will be as shown in fig herefront and rear howeverbefore inserting an element in queuewe must check for overflow conditions an overflow will occur when step if rear max- write overflow we try to insert an element into queue that is already full goto step when rear max where max is the size of the queuewe [end of ifhave an overflow condition note that we have written max step if front - and rear - because the index starts from set front rear else similarlybefore deleting an element from queuewe set rear rear must check for underflow conditions an underflow condition [end of ifoccurs when we try to delete an element from queue that step set queue[rearnum is already empty if front - and rear - it means there step exit is no element in the queue let us now look at figs and which show the algorithms to insert and delete an element figure algorithm to insert an element in from queue queue figure shows the algorithm to insert an element in queue in step we first check for the overflow condition in step if front - or front rear step we check if the queue is empty in case the queue is write underflow emptythen both front and rear are set to zeroso that the else set val queue[frontnew value can be stored at the th location otherwiseif the set front front queue already has some valuesthen rear is incremented so [end of ifthat it points to the next location in the array in step the step exit value is stored in the queue at the location pointed by rear figure shows the algorithm to delete an element from figure algorithm to delete an element from queue in step we check for underflow condition an queue underflow occurs if front - or front rear howeverif queue has some valuesthen front is incremented so that it now points to the next value in the queue programming example write program to implement linear queue ##include #include
24,475
#define max /changing this value will change length of array int queue[max]int front - rear - void insert(void)int delete_element(void)int peek(void)void display(void)int main(int optionvaldo printf("\ \ ****main menu *****")printf("\ insert an element")printf("\ delete an element")printf("\ peek")printf("\ display the queue")printf("\ exit")printf("\ enter your option ")scanf("% "&option)switch(optioncase insert()breakcase val delete_element()if (val !- printf("\ the number deleted is % "val)breakcase val peek()if (val !- printf("\ the first value in queue is % "val)breakcase display()break}while(option ! )getch()return void insert(int numprintf("\ enter the number to be inserted in the queue ")scanf("% "&num)if(rear =max- printf("\ overflow")else if(front =- &rear =- front rear else rear++queue[rearnumint delete_element(int val
24,476
data structures using if(front =- |front>rearprintf("\ underflow")return - else val queue[front]front++if(front rearfront rear - return valint peek(if(front==- |front>rearprintf("\ queue is empty")return - else return queue[front]void display(int iprintf("\ ")if(front =- |front rearprintf("\ queue is empty")else for( front; <rear; ++printf("\ % "queue[ ])output ****main menu ***** insert an element delete an element peek display the queue exit enter your option enter the number to be inserted in the queue note the process of inserting an element in the queue is called enqueueand the process of deleting an element from the queue is called dequeue linked representation of queues we have seen how queue is created using an array although this technique of creating queue is easyits drawback is that the array must be declared to have some fixed size if we allocate space for elements in the queue and it hardly uses - locationsthen half of the space will
24,477
be wasted and in case we allocate less memory locations for queue that might end up growing large and largethen lot of re-allocations will have to be donethereby creating lot of overhead and consuming lot of time in case the queue is very small one or its maximum size is known in advancethen the array implementation of the queue gives an efficient implementation but if the array size cannot be determined in advancethe other alternativei the linked representation is used the storage requirement of linked representation of queue with elements is (nand the typical time requirement for operations is ( in linked queueevery element has two partsone that stores the data and another that stores the address of the next element the start pointer of the linked list is used as front herewe will also use another pointer called rearwhich will store the address of the last element in the queue all insertions will be done at the rear end and all the deletions will be done at the front end if front rear nullthen it indicates that the queue is empty the linked representation of queue is shown in fig operations on linked queues queue has two basic operationsinsert and delete the insert operation adds an element to the end of the queueand the delete operation removes an element from the front or the start of the queue apart from thisthere is another operation peek which returns the value of the first element of the queue insert operation the insert operation is used to insert an element into queue the new element is added as the last element of the queue consider the linked queue shown in fig to insert an element with value we first check if front=null if the condition holdsthen front rear the queue is empty sowe allocate memory for figure linked queue new nodestore the value in its data part and null in its next part the new node will then be called both front and rear howeverif front front rear !nullthen we will insert the new node at the figure linked queue rear end of the linked queue and name this new node as rear thusthe updated queue becomes as shown in fig front rear figure shows the algorithm to insert figure linked queue after inserting new node an element in linked queue in step the memory is allocated for the new node in step step allocate memory for the new node and name the data part of the new node is initialized it as ptr with the value to be stored in the node in step step set ptr -data val step if front null we check if the new node is the first node set front rear ptr of the linked queue this is done by checking set front -next rear -next null if front null if this is the casethen the new else set rear -next ptr node is tagged as front as well as rear also null set rear ptr is stored in the next part of the node (which is set rear -next null also the front and the rear nodehoweverif [end of ifstep end the new node is not the first node in the listthen it is added at the rear end of the linked queue figure algorithm to insert an element in linked queue (or the last node of the queue
24,478
data structures using delete operation the delete operation is used to delete the element that is first inserted in queuei the element whose address is stored in front howeverbefore deleting the valuewe must first check if front=null because if this is the casethen the queue is empty and no more deletions can be done if an attempt is made to delete value from queue that is already emptyan underflow front rear message is printed consider the queue shown figure linked queue in fig to delete an elementwe first check if rear front front=null if the condition is falsethen we figure linked queue after deletion of an element delete the first node pointed by front the front will now point to the second element of the linked queue thusthe updated queue becomes as shown in step if front null write "underflowfig go to step figure shows the algorithm to delete an element from [end of ifa linked queue in step we first check for the underflow step set ptr front step set front front -next condition if the condition is truethen an appropriate message step free ptr is displayedotherwise in step we use pointer ptr that step end points to front in step front is made to point to the next node in sequence in step the memory occupied by ptr is figure algorithm to delete an element given back to the free pool from linked queue programming example write program to implement linked queue #include #include #include struct node int datastruct node *next}struct queue struct node *frontstruct node *rear}struct queue *qvoid create_queue(struct queue *)struct queue *insert(struct queue *,int)struct queue *delete_element(struct queue *)struct queue *display(struct queue *)int peek(struct queue *)int main(int valoptioncreate_queue( )clrscr()do printf("\ *****main menu*****")printf("\ insert")printf("\ delete")
24,479
printf("\ peek")printf("\ display")printf("\ exit")printf("\ enter your option ")scanf("% "&option)switch(optioncase printf("\ enter the number to insert in the queue:")scanf("% "&val) insert( ,val)breakcase delete_element( )breakcase val peek( )if(val- printf("\ the value at front of queue is % "val)breakcase display( )break}while(option ! )getch()return void create_queue(struct queue *qq -rear nullq -front nullstruct queue *insert(struct queue * ,int valstruct node *ptrptr (struct node*)malloc(sizeof(struct node))ptr -data valif( -front =nullq -front ptrq -rear ptrq -front -next -rear -next nullelse -rear -next ptrq -rear ptrq -rear -next nullreturn qstruct queue *display(struct queue *qstruct node *ptrptr -frontif(ptr =nullprintf("\ queue is empty")else printf("\ ")
24,480
data structures using while(ptr!= -rearprintf("% \ "ptr -data)ptr ptr -nextprintf("% \ "ptr -data)return qstruct queue *delete_element(struct queue *qstruct node *ptrptr -frontif( -front =nullprintf("\ underflow")else -front -front -nextprintf("\ the value being deleted is % "ptr -data)free(ptr)return qint peek(struct queue *qif( ->front==nullprintf("\ queue is empty")return - else return ->front->dataoutput *****main menu**** insert delete peek display exit enter your option queue is empty enter your option types of queues queue data structure can be classified into the following types circular queue deque priority queue multiple queue we will discuss each of these queues in detail in the following sections circular queues in linear queueswe have discussed so far that insertions can be done only at one end called the rear and deletions are always done from the other end called the front look at the queue shown in fig figure linear queue herefront and rear
24,481
nowif you want to insert another valueit will not be possible because the queue is completely full there is no empty space where the value can be inserted consider scenario in which two successive deletions are made the queue will then be given as shown in fig figure queue after two successive deletions herefront and rear suppose we want to insert new element in the queue shown in fig even though there is space availablethe overflow condition still exists because the condition rear max still holds true this is major drawback of linear queue to resolve this problemwe have two solutions firstshift the elements to [ the left so that the vacant space can be occupied and utilized efficiently but [ [ this can be very time-consumingespecially when the queue is quite large the second option is to use circular queue in the circular queuethe [ [ first index comes right after the last index conceptuallyyou can think of [ [ circular queue as shown in fig the circular queue will be full only when front and rear max figure circular queue circular queue is implemented in the same manner as linear queue is implemented the only difference will be in the code that performs insertion and deletion front rear operations for insertionwe now have to check figure full queue for the following three conditions if front and rear max then the front rear circular queue is full look at the queue increment rear so that it points to location and insert the value here given in fig which illustrates this point figure queue with vacant locations if rear !max then rear will be incremented and the value will be inserted front rear as illustrated in fig set rear and insert the value here if front ! and rear max then it means that the queue is not full soset rear figure inserting an element in circular queue and insert the new element thereas shown step if front and rear max in fig write "overflowlet us look at fig which shows the algorithm goto step to insert an element in circular queue in step we [end of ifcheck for the overflow condition in step we make two step if front - and rear - set front rear checks first to see if the queue is emptyand second to else if rear max and front !see if the rear end has already reached the maximum set rear capacity while there are certain free locations before else set rear rear the front end in step the value is stored in the queue [end of ifat the location pointed by rear step set queue[rearval after seeing how new element is added in circular step exit queuelet us now discuss how deletions are performed in this case to delete an elementagain we check for figure algorithm to insert an element in three conditions circular queue
24,482
data structures using front rear - figure empty queue front rear delete this element and set rear front - figure queue with single element rear front look at fig if front - then there are no elements in the queue soan underflow condition will be reported if the queue is not empty and front rearthen after deleting the element at the front the queue becomes empty and so front and rear are set to - this is illustrated in fig if the queue is not empty and front max- then after deleting the element at the frontfront is set to this is shown in fig let us look at fig which shows the algorithm to delete an element from circular delete this element and set front queue in step we check for the underflow figure queue where front max- before deletion condition in step the value of the queue at the location pointed by front is stored in val in step step if front - we make two checks first to see if the queue has become write "underflowempty after deletion and second to see if front has reached goto step [end of ifthe maximum capacity of the queue the value of front step set val queue[frontis then updated based on the outcome of these checks step if front rear set front rear - else if front max - set front else set front front [end of if[end of ifstep exit figure algorithm to delete an element from circular queue programming example write program to implement circular queue #include #include #define max int queue[max]int front=- rear=- void insert(void)int delete_element(void)int peek(void)void display(void)int main(int optionvalclrscr()do printf("\ ****main menu *****")printf("\ insert an element")printf("\ delete an element")printf("\ peek")printf("\ display the queue")printf("\ exit")printf("\ enter your option ")scanf("% "&option)switch(optioncase insert()breakcase val delete_element()if(val!=-
24,483
printf("\ the number deleted is % "val)breakcase val peek()if(val!=- printf("\ the first value in queue is % "val)breakcase display()break}while(option!= )getch()return void insert(int numprintf("\ enter the number to be inserted in the queue ")scanf("% "&num)if(front== &rear==max- printf("\ overflow")else if(front==- &rear==- front=rear= queue[rear]=numelse if(rear==max- &front!= rear= queue[rear]=numelse rear++queue[rear]=numint delete_element(int valif(front==- &rear==- printf("\ underflow")return - val queue[front]if(front==rearfront=rear=- else if(front==max- front= else front++return valint peek(if(front==- &rear==- printf("\ queue is empty")return -
24,484
data structures using else return queue[front]void display(int iprintf("\ ")if (front ==- &rear=- printf ("\ queue is empty")else if(front<rearfor( =front; <=rear; ++printf("\ % "queue[ ])else for( =front; <max; ++printf("\ % "queue[ ])for( = ; <=rear; ++printf("\ % "queue[ ])output ****main menu **** insert an element delete an element peek display the queue exit enter your option enter the number to be inserted in the queue enter your option the number deleted is enter your option queue is empty enter your option deques deque (pronounced as 'deckor 'dequeue'is list in which the elements can be inserted or deleted at either end it is also known as head-tail linked list because elements can be added to or removed from either the front (heador the back (tailend howeverno element can be added and deleted from the middle in the computer' memorya deque is implemented using either circular array or circular doubly linked list in dequetwo pointers are maintainedleft and rightwhich point to either end of the deque the elements in deque extend from the left end to the right end and since it is circulardequeue[ - is followed by dequeue[ consider the deques shown in fig there are two variants of double-ended queue they include input restricted deque in this dequeue insertions can be done only at one of the ends left right while deletions can be done from both ends output restricted deque in this dequeueright left deletions can be done only at one of the endsfigure double-ended queues while insertions can be done on both ends
24,485
programming example write program to implement input and output restricted deques #include #include #define max int deque[max]int left - right - void input_deque(void)void output_deque(void)void insert_left(void)void insert_right(void)void delete_left(void)void delete_right(void)void display(void)int main(int optionclrscr()printf("\ *****main menu*****")printf("\ input restricted deque")printf("\ output restricted deque")printf("enter your option ")scanf("% ",&option)switch(optioncase input_deque()breakcase output_deque()breakreturn void input_deque(int optiondo printf("\ input restricted deque")printf("\ insert at right")printf("\ delete from left")printf("\ delete from right")printf("\ display")printf("\ quit")printf("\ enter your option ")scanf("% ",&option)switch(optioncase insert_right()breakcase delete_left()breakcase delete_right()breakcase display()break}while(option!= )
24,486
data structures using void output_deque(int optiondo printf("output restricted deque")printf("\ insert at right")printf("\ insert at left")printf("\ delete from left")printf("\ display")printf("\ quit")printf("\ enter your option ")scanf("% ",&option)switch(optioncase insert_right()breakcase insert_left()breakcase delete_left()breakcase display()break}while(option!= )void insert_right(int valprintf("\ enter the value to be added:")scanf("% "&val)if((left = &right =max- |(left =right+ )printf("\ overflow")returnif (left =- /if queue is initially empty *left right else if(right =max- /*right is at last position of queue *right else right right+ deque[rightval void insert_left(int valprintf("\ enter the value to be added:")scanf("% "&val)if((left = &right =max- |(left =right+ )printf("\ overflow")return
24,487
if (left =- )/*if queue is initially empty*left right else if(left = left=max- else left=left- deque[leftvalvoid delete_left(if (left =- printf("\ underflow")return printf("\ the deleted element is % "deque[left])if(left =right/*queue has only one element *left - right - else if(left =max- left else left left+ void delete_right(if (left =- printf("\ underflow")return printf("\ the element deleted is % "deque[right])if(left =right/*queue has only one element*left - right - else if(right = right=max- else right=right- void display(int front leftrear rightif(front =- printf("\ queue is empty")returnprintf("\ the elements of the queue are ")
24,488
data structures using if(front <rear while(front <rearprintf("% ",deque[front])front++else while(front <max- printf("% "deque[front])front++front while(front <rearprintf("% ",deque[front])front++printf("\ ")output ****main menu **** input restricted deque output restricted deque enter your option input restricted dequeue insert at right delete from left delete from right display quit enter your option enter the value to be added enter the value to be added enter your option the deleted element is enter your option priority queues priority queue is data structure in which each element is assigned priority the priority of the element will be used to determine the order in which the elements will be processed the general rules of processing the elements of priority queue are an element with higher priority is processed before an element with lower priority two elements with the same priority are processed on first-come-first-served (fcfsbasis priority queue can be thought of as modified queue in which when an element has to be removed from the queuethe one with the highest-priority is retrieved first the priority of the element can be set based on various factors priority queues are widely used in operating systems to execute the highest priority process first the priority of the process may be set based on the cpu time it requires to get executed completely for exampleif there are three processeswhere the first process needs ns to completethe second process needs nsand the third process needs nsthen the second process will have the highest priority and will thus be the first to be executed howevercpu time is not the only factor that determines the priorityrather it is just one among several factors another factor is the importance of one process over another in case we have to run two processes at the same timewhere one process is concerned with online order booking
24,489
and the second with printing of stock detailsthen obviously the online booking is more important and must be executed first implementation of priority queue there are two ways to implement priority queue we can either use sorted list to store the elements so that when an element has to be taken outthe queue will not have to be searched for the element with the highest priority or we can use an unsorted list so that insertions are always done at the end of the list every time when an element has to be removed from the listthe element with the highest priority will be searched and removed while sorted list takes (ntime to insert an element in the listit takes only ( time to delete an element on the contraryan unsorted list will take ( time to insert an element and (ntime to delete an element from the list practicallyboth these techniques are inefficient and usually blend of these two approaches is adopted that takes roughly (log ntime or less linked representation of priority queue in the computer memorya priority queue can be represented using arrays or linked lists when priority queue is implemented using linked listthen every node of the list will have three parts(athe information or data part(bthe priority number of the elementand (cthe address of the next element if we are using sorted linked listthen the element with the higher priority will precede the element with the lower priority consider the priority queue shown in fig figure priority queue lower priority number means higher priority for exampleif there are two elements and bwhere has priority number and has priority number then will be processed before as it has higher priority than the priority queue in fig is sorted priority queue having six elements from the queuewe cannot make out whether was inserted before or whether joined the queue before because the list is not sorted based on fcfs herethe element with higher priority comes before the element with lower priority howeverwe can definitely say that was inserted in the queue before because when two elements have the same priority the elements are arranged and processed on fcfs principle insertion when new element has to be inserted in priority queuewe have to traverse the entire list until we find node that has priority lower than that of the new element the new node is inserted before the node with the lower priority howeverif there exists an element that has the same priority as the new elementthe new element is inserted after that element for exampleconsider the priority queue shown in fig figure priority queue if we have to insert new element with data and priority number then the element will be inserted before that has priority number which is lower priority than that of the new element sothe priority queue now becomes as shown in fig figure priority queue after insertion of new node
24,490
data structures using howeverif we have new element with data and priority number then the element will be inserted after bas both these elements have the same priority but the insertions are done on fcfs basis as shown in fig figure priority queue after insertion of new node deletion deletion is very simple process in this case the first node of the list will be deleted and the data of that node will be processed first array representation of priority queue when arrays are used to implement priority queuethen separate queue for each priority number is maintained each of these queues will be implemented using circular arrays or circular queues every individual queue will have its own front and rear pointers we use two-dimensional array for this purpose where each queue will be allocated the same amount of space look at the two-dimensional representation of priority queue given below given the front and rear values of each queuethe two-dimensional matrix can be formed as shown in fig front[kand rear[kcontain the front and rear values of row kwhere is the priority number note that here we are assuming that the row and column indices start from not obviouslywhile programmingwe will not take such assumptions insertion to insert new element with priority front rear in the priority queueadd the element at the rear end of row kwhere is the row number as well as the priority number of that element for exampleif we have to insert an element with priority number then the priority queue will be given as shown in fig figure priority queue matrix front rear figure priority queue matrix after insertion of new element deletion to delete an elementwe find the first nonempty queue and then process the front element of the first non-empty queue in our priority queuethe first non-empty queue is the one with priority number and the front element is aso will be deleted and processed first in technical termsfind the element with the smallest ksuch that front[ !null programming example write program to implement priority queue #include #include #include struct node int dataint prioritystruct node *next
24,491
struct node *start=nullstruct node *insert(struct node *)struct node *delete(struct node *)void display(struct node *)int main(int optionclrscr()do printf("\ *****main menu*****)printf("\ insert")printf("\ delete")printf("\ display")printf("\ exit")printf("\ enter your option ")scanf"% "&option)switch(optioncase start=insert(start)breakcase start delete(start)breakcase display(start)break}while(option!= )struct node *insert(struct node *startint valpristruct node *ptr*pptr (struct node *)malloc(sizeof(struct node))printf("\ enter the value and its priority )scanf"% % "&val&pri)ptr->data valptr->priority priif(start==null |pri priority ptr->next startstart ptrelse startwhile( ->next !null & ->next->priority <prip ->nextptr->next ->nextp->next ptrreturn startstruct node *delete(struct node *startstruct node *ptrif(start =nullprintf("\ underflow)returnelse
24,492
data structures using ptr startprintf("\ deleted item is% "ptr->data)start start->nextfree(ptr)return startvoid display(struct node *startstruct node *ptrptr startif(start =nullprintf("\nqueue is empty)else printf("\ priority queue is )while(ptr !nullprintf"\ % [priority=% ]"ptr->dataptr->priority )ptr=ptr->nextoutput *****main menu**** insert delete display exit enter your option enter the value and its priority enter the value and its priority enter your option priority queue is [priority [priority enter your option multiple queues when we implement queue using an arraythe size of the array must be known in advance if the queue is allocated less spacethen frequent overflow conditions will be encountered to deal with this problemthe code will have to be modified to reallocate more space for the array in case we allocate large amount of space for the queueit will result in sheer wastage of the memory thusthere lies tradeoff between the frequency of overflows and the space allocated so better solution to deal with this problem is to have multiple queues or to have more than one queue in the same array of sufficient size figure illustrates this concept in the figurean array queue[nis used to represent two queuesqueue and queue the value of is such that the combined size of both the queues will never exceed while operating on these queuesit is important to note one thing--queue - - - - will grow from left to rightwhereas queue will grow from right to left at the same time queue queue extending the concept to multiple queuesa queue figure multiple queues can also be used to represent number of queues in the same array that isif we have queue[ ] [ [ [ [ [ [ [ [ [ [ then each queue will be allocated an equal amount of space bounded by indices [iand [ithis is shown in fig figure multiple queues
24,493
programming example write program to implement multiple queues #include #include #define max int queue[max]reara=- ,fronta=- rearb=maxfrontb maxvoid inserta(int valif(reara==rearb - printf("\ overflow")else if(reara ==- &fronta =- reara fronta queue[rearavalelse queue[++rearavalint deletea(int valif(fronta==- printf("\ underflow")return - else val queue[fronta]fronta++if (fronta>rearafronta=reara=- return valvoid display_queuea(int iif(fronta==- printf("\ queue is empty")else for( =fronta; <=reara; ++printf("\ % ",queue[ ])void insertb(int valif(reara==rearb- printf("\ overflow")else if(rearb =max &frontb =maxrearb frontb max- queue[rearbvalelse queue[--rearbval
24,494
data structures using int deleteb(int valif(frontb==maxprintf("\ underflow")return - else val queue[frontb]frontb--if (frontb<rearbfrontb=rearb=maxreturn valvoid display_queueb(int iif(frontb==maxprintf("\ queue is empty")else for( =frontb; >=rearb; --printf("\ % ",queue[ ])int main(int optionvalclrscr()do printf("\ *******menu******")printf("\ insert in queue ")printf("\ insert in queue ")printf("\ delete from queue ")printf("\ delete from queue ")printf("\ display queue ")printf("\ display queue ")printf("\ exit")printf("\ enter your option ")scanf("% ",&option)switch(optioncase printf("\ enter the value to be inserted in queue ")scanf("% ",&val)inserta(val)breakcase printf("\ enter the value to be inserted in queue ")scanf("% ",&val)insertb(val)breakcase val=deletea()if(val!=- printf("\ the value deleted from queue % ",val)breakcase val=deleteb()if(val!=-
24,495
printf("\ the value deleted from queue % ",val)breakcase printf("\ the contents of queue are \ ")display_queuea()breakcase printf("\ the contents of queue are \ ")display_queueb()break}while(option!= )getch()output *******menu****** insert in queue insert in queue delete from queue delete from queue display queue display queue exit enter your option enter the value to be inserted in queue enter the value to be inserted in queue enter your option the contents of queue are enter your option applications of queues queues are widely used as waiting lists for single shared resource like printerdiskcpu queues are used to transfer data asynchronously (data not necessarily received at same rate as sentbetween two processes (io buffers) pipesfile iosockets queues are used as buffers on mp players and portable cd playersipod playlist queues are used in playlist for jukebox to add songs to the endplay from the front of the list queues are used in operating system for handling interrupts when programming real-time system that can be interruptedfor exampleby mouse clickit is necessary to process the interrupts immediatelybefore proceeding with the current job if the interrupts have to be handled in the order of arrivalthen fifo queue is the appropriate data structure josephus problem let us see how queues can be used for finding solution to the josephus problem in josephus problemn people stand in circle waiting to be executed the counting starts at some point in the circle and proceeds in specific direction around the circle in each stepa certain number of people are skipped and the next person is executed (or eliminatedthe elimination of people makes the circle smaller and smaller at the last steponly one person remains who is declared the 'winnerthereforeif there are number of people and number which indicates that - people are skipped and -th person in the circle is eliminatedthen the problem is to choose position in the initial circle so that the given person becomes the winner for exampleif there are (npeople and every second (kperson is eliminatedthen first the person at position is eliminated followed by the person at position followed by person at position and finally the person at position is eliminated thereforethe person at position becomes the winner
24,496
data structures using try the same process with and = you will find that person at position is the winner the elimination goes in the sequence of and programming example write program which finds the solution of josephus problem using circular linked list #include #include #include struct node int player_idstruct node *next}struct node *start*ptr*new_nodeint main(int nkicountclrscr()printf("\ enter the number of players ")scanf("% "& )printf("\ enter the value of (every kth player gets eliminated)")scanf("% "& )/create circular linked list containing all the players start malloc(sizeof(struct node))start->player_id ptr startfor ( <ni++new_node malloc(sizeof(struct node))ptr->next new_nodenew_node->player_id inew_node->next=startptr=new_nodefor (count ncount count--for ( ++iptr ptr->nextptr->next ptr->next->next/remove the eliminated player from the circular linked list printf("\ the winner is player % "ptr->player_id)getche()return output enter the number of players enter the value of (every kth player gets eliminated) the winner is player
24,497
points to remember queue is fifo data structure in which the element that is inserted first is the first one to be taken out the elements in queue are added at one end called the rear and removed from the other end called the front in the computer ' memoryqueues can be implemented using both arrays and linked lists the storage requirement of linked representation of queue with elements is (nand the typical time requirement for operations is ( in circular queuethe first index comes after the last index multiple queues means to have more than one queue in the same array of sufficient size deque is list in which elements can be inserted or deleted at either end it is also known as headtail linked list because elements can be added to or removed from the front (heador back (tailhoweverno element can be added or deleted from the middle in the computer' memorya deque is implemented using either circular array or circular doubly linked list in an input restricted dequeinsertions can be done only at one endwhile deletions can be done from both the ends in an output restricted dequedeletions can be done only at one endwhile insertions can be done at both the ends priority queue is data structure in which each element is assigned priority the priority of the element will be used to determine the order in which the elements will be processed when priority queue is implemented using linked listthen every node of the list will have three parts(athe information or data part(bthe priority number of the elementand (cthe address of the next element exercises review questions what is priority queuegive its applications explain the concept of circular queuehow is it better than linear queue why do we use multiple queues draw the queue structure in each case when the following operations are performed on an empty queue (aadd abcdef (bdelete two letters (cadd (dadd (edelete four letters (fadd consider the queue given below which has front and rear now perform the following operations on the queue(aadd (bdelete two letters (cadd (dadd (edelete four letters (fadd consider the dequeue given below which has left and right now perform the following operations on the queue(aadd on the left (badd on the right (cadd on the right (ddelete two letters from left (eadd on the right (fadd on the left (gdelete two letters from right programming exercises write program to calculate the number of items in queue write program to create linear queue of values write program to create queue using arrays which permits insertion at both the ends write program to implement dequeue with the help of linked list write program to create queue which permits insertion at any vacant location at the rear end write program to create queue using arrays which permits deletion from both the ends write program to create queue using arrays which permits insertion and deletion at both the ends
24,498
data structures using write program to implement priority queue write program to create queue from stack write program to create stack from queue write program to reverse the elements of queue write program to input two queues and compare their contents multiple-choice questions line in grocery store represents (astack (bqueue (clinked list (darray in queueinsertion is done at (arear (bfront (cback (dtop the function that deletes values from queue is called (aenqueue (bdequeue (cpop (dpeek typical time requirement for operations on queues is (ao( (bo( (co(log (do( the circular queue will be full only when (afront max - and rear max - (bfront and rear max - (cfront max - and rear (dfront and rear true or false queue stores elements in manner such that the first element is at the beginning of the list and the last element is at the end of the list elements in priority queue are processed sequentially in linked queuea maximum of elements can be added conceptually linked queue is same as that of linear queue the size of linked queue cannot change during run time in priority queuetwo elements with the same priority are processed on fcfs basis output-restricted deque allows deletions to be done only at one end of the dequeuewhile insertions can be done at both the ends if front=max and rear then the circular queue is full fill in the blanks new nodes are added at of the queue allows insertion of elements at either ends but not in the middle the typical time requirement for operations in linked queue is in insertions can be done only at one endwhile deletions can be done from both the ends dequeue is implemented using are appropriate data structures to process batch computer programs submitted to the computer centre are appropriate data structures to process list of employees having contract for seniority system for hiring and firing
24,499
trees learning objective so farwe have discussed linear data structures such as arraysstringsstacksand queues in this we will learn about non-linear data structure called tree tree is structure which is mainly used to store data that is hierarchical in nature in this we will first discuss general trees and then binary trees these binary trees are used to form binary search trees and heaps they are widely used to manipulate arithmetic expressionsconstruct symbol tablesand for syntax analysis introduction tree is recursively defined as set of one or more nodes where one node is designated as the root of the tree and all the remaining nodes can be partitioned into non-empty sets each of which is sub-tree of the root figure shows tree where node is the root nodenodes bcand are children of the root node and form sub-trees of the tree rooted at node basic terminology root node the root node is the topmost node in the tree if nullthen it means the tree is empty sub-trees if the root node is not nullthen the trees and are called the sub-trees of leaf node node that has no children is called the leaf node or the terminal node path sequence of consecutive edges is called path for examplein fig the path from the root node to node is given asadand ancestor node an ancestor of node is any predecessor node on the path from root to that node the root node does not have any ancestors in the tree given in fig nodes acand are the ancestors of node