Sei sulla pagina 1di 103

Elementary Data Structures

ELEMENTRY DATA STRUCTURES

Approach to study this document: This session is divided into 10 different lectures. Please try to complete one lecture in one sitting which will hardly take 1 minutes as you are already aware of all these concepts. !t will "ust #rush up your DS concepts and help you to #uild stronger DS later on.

Page 1 of 103

Elementary Data Structures

Lecture No. 01
Summary
!ntroduction to Data Structures Selecting a Data Structure Data Structure Philosophy %oals of this &ourse 'rray (ist data structure

)elcome to the course of data structure. This is very important su#"ect as the topics covered in it will #e encountered #y you again and again in the future courses. Due to its great applica#ility* this is usually called as the foundation course. +ou have already studied !ntroduction to programming using & and &,, and used some data structures. The focus of that course was on how to carry out programming with the use of & and &,, languages #esides the resolution of different pro#lems. !n this course* we will continue pro#lem solving and see that the organi-ation of data in some cases is of immense importance. Therefore* the data will #e stored in a special way so that the re.uired result should #e calculated as fast as possi#le. /ollowing are the goals of this course0 Prepare the students for 1and is a pre2re.uisite for3 the more advanced material students will encounter in later courses. &over well2known data structures such as dynamic arrays* linked lists* stacks* .ueues* trees and graphs. !mplement data structures in &,, +ou have already studied the dynamic arrays in the previous course. )e will now discuss linked lists* stacks* .ueues* trees and graphs and try to resolve the pro#lems

Page $ of 103

Elementary Data Structures with the help of these data structures. These structures will #e implemented in &,, language. )e will also do programming assignments to see the usage and importance of these structures.

Introduction to Data Structures


(et4s discuss why we need data structures and what sort of pro#lems can #e solved with their use. Data structures help us to organi-e the data in the computer* resulting in more efficient programs. 'n efficient program e5ecutes faster and helps minimi-e the usage of resources like memory* disk. &omputers are getting more powerful with the passage of time with the increase in &P6 speed in %7-* availa#ility of faster network and the ma5imi-ation of disk space. Therefore people have started solving more and more comple5 pro#lems. 's computer applications are #ecoming comple5* so there is need for more resources. This does not mean that we should #uy a new computer to make the application e5ecute faster. 8ur effort should #e to ensue that the solution is achieved with the help of programming* data structures and algorithm. )hat does organi-ing the data mean9 !t means that the data should #e arranged in a way that it is easily accessi#le. The data is inside the computer and we want to see it. )e may also perform some calculations on it. Suppose the data contains some num#ers and the programmer wants to calculate the average* standard deviation etc. :ay #e we have a list of names and want to search a particular name in it. To solve such pro#lems* data structures and algorithm are used. Sometimes you may reali-e that the application is too slow and taking more time. There are chances that it may #e due to the data structure used* not due to the &P6 speed and memory. )e will see such e5amples. !n the assignments* you will also check whether the data structure in the program is #eneficial or not. +ou may have two data structures and try to decide which one is more suita#le for the resolution of the pro#lem. 's discussed earlier* a solution is said to #e efficient if it solves the pro#lem within its resource constraints. )hat does it mean9 !n the computer* we have hard disk* memory and other hardware. Secondly we have time. Suppose you have some program that solves the pro#lem #ut takes two months. !t will #e of no use. 6sually* you don4t have this much time and cannot wait for two months. Suppose the data is too huge to #e stored in disk. 7ere we have also the pro#lem of resources. This means that we have to write programs considering the resources to achieve some solution as soon as possi#le. There is always cost associated with these resources. )e may need a faster and #etter &P6 which can #e purchased. Sometimes* we may need to #uy memory. 's long as data structures and programs are concerned* you have to invest your own time for this. )hile working in a company* you will #e paid for this. 'll these re.uirements including computer* your time and computer time will decide that the solution you have provided is suita#le or not. !f its advantages are not o#tained* then either program or computer is not good. So the purchase of a faster computer* while studying this course* does not necessarily help us in the resolution of the pro#lem. !n the course of ;&omputer 'rchitecture< you Page 3 of 103

Elementary Data Structures must have seen how the more efficient solutions can #e prepared with the hardware. !n this course* we will use the software i.e. data structures* algorithms and the recipes through which the computer pro#lems may #e resolved with a faster solution.

Selecting a Data Structure


7ow can we select the data structure needed to solve a pro#lem9 +ou have already studied where to use array and the si-e of array and when and where to use the pointers etc. /irst of all* we have to analy-e the pro#lem to determine the resource constraints that a solution must meet. Suppose* the data is so huge i.e. in %ega #ytes 1%>s3 while the disc space availa#le with us is "ust $00 :ega #ytes. This pro#lem can not #e solved with programming. ?ather* we will have to #uy a new disk. Secondly* it is necessary to determine the #asic operations that must #e supported. @uantify the resource constraints for each operation. )hat does it mean9 Suppose you have to insert the data in the computer or data#ase and have to search some data item. (et4s take the e5ample of telephone directory. Suppose there are eight million names in the directory. Aow someone asks you a#out the name of some particular person. +ou want that this .uery should #e answered as soon as possi#le. +ou may add or delete some data. !t will #e advisa#le to consider all these operations when you select some data structure. /inally select the data structure that meets these re.uirements the ma5imum. )ithout* sufficient e5perience* it will #e difficult to determine which one is the #est data structure. )e can get the help from internet* #ooks or from someone whom you know for already getting the pro#lems solved. )e may find a similar e5ample and try to use it. 'fter this course* you will #e familiar with the data structures and algorithms that are used to solve the computer pro#lems. Aow you have selected the data structure. Suppose a programmer has inserted some data and wants to insert more data. This data will #e inserted in the #eginning of the e5isting data* or in the middle or in the end of the data. (et4s talk a#out the arrays and suppose you have an array of si-e hundred. Data may #e lying in the first fifty locations of this array. Aow you have to insert data in the start of this array. )hat will you do9 +ou have to move the e5isting data 1fifty locations3 to the right so that we get space to insert new data. 8ther way round* there is no space in the start. Suppose you have to insert the data at $ th location. /or this purpose* it is #etter to move the data from $Bth to 0th locationsC otherwise we will not have space to insert this new data at $ th location. Aow we have to see whether the data can #e deleted or not. Suppose you are asked to delete the data at $Dth position. 7ow can we do that9 )hat will we do with the space created at $Dth position9 Thirdly* is all the data processed in some well2defined order or random access allowed9 'gain take the e5ample of arrays. )e can get the data from 0th position and traverse the array till its 0th position. Suppose we want to get the data* at first from 0th location and then from 13th. !t means that there is no order or se.uence. )e want

Page = of 103

Elementary Data Structures to access the data randomly. ?andom access means that we can4t say what will #e the ne5t position to get the data or insert the data.

Data Structure Philosophy


(et4s talk a#out the philosophy of data structure. Each data structure has costs and #enefits. 'ny data structure used in your program will have some #enefits. /or this* you have to pay price. That can #e computer resources or the time. 'lso keep in mind that you are solving this pro#lem for some client. !f the program is not efficient* the client will not #uy it. !n rare cases* a data structure may #e #etter than another one in all situations. !t means that you may think that the array is good enough for all the pro#lems. +et this is not necessary. !n different situations* different data structures will #e suita#le. Sometimes you will reali-e that two different data structures are suita#le for the pro#lem. !n such a case* you have to choose the one that is more appropriate. 'n important skill this course is going to lend to the students is use the data structure according to the situation. +ou will learn the programming in a way that it will #e possi#le to replace the one data structure with the other one if it does not prove suita#le. )e will replace the data structure so that the rest of the program is not affected. +ou will also have to attain this skill as a good programmer. There are three #asic things associated with data structures. ' data structure re.uires0 space for each data item it stores time to perform each #asic operation programming effort

Goals of this Course


?einforce the concept that costs and #enefits e5ist for every data structure. )e will learn this with practice. (earn the commonly used data structures. These form a programmerEs #asic data structure ;toolkit<. !n the previous course* you have learned how to form a loop* functions* use of arrays* classes and how to write programs for different pro#lems. !n this course* you will make use of data structures and have a feeling that there is #ag full of different data structures. !n case of some pro#lem* you will get a data structure from the toolkit and use some suita#le data structure. 6nderstand how to measure the cost of a data structure or program. These techni.ues also allow you to "udge the merits of new data structures that you or others might develop. 't times* you may have two suita#le data structures for some pro#lem. These can #e tried one #y one to ad"udge which one is #etter one. 7ow can you decide which data structure is #etter than other. /irstly* a programmer can do it #y writing two programs using different data structure while solving the same pro#lem. Aow e5ecute #oth data structures. 8ne gives the result #efore the other. The data structure that

Page of 103

Elementary Data Structures gives results first is #etter than the other one. >ut sometimes* the data grows too large in the pro#lem. Suppose we want to solve some pro#lem having names and the data of names grows to10 lakhs 1one million3. Aow when you run #oth programs* the second program runs faster. )hat does it mean9 !s the data structure used in program one not correct9 This is not true. The si-e of the data* #eing manipulated in the program can grow or shrink. +ou will also see that some data structures are good for small data while the others may suit to huge data. >ut the pro#lem is how can we determine that the data in future will increase or decrease. )e should have some way to take decision in this regard. !n this course we will do some mathematical analysis and see which data structure is #etter one.

Arrays
+ou have already studied a#out arrays and are well2versed with the techni.ues to utili-e these data structures. 7ere we will discuss how arrays can #e used to solve computer pro#lems. &onsider the following program0 main1 int argc* charFF argv 3 G int 5HBIC int "C for1" J 0C " K BC ",,3 5H"I J $ F "C L )e have declared an int array of si5 elements and initiali-ed it in the loop. (et4s revise some of the array concepts. The declaration of array is as int x[6]; or float x[6]; or double x[6]; +ou have already done these in your programming assignments. 'n array is collection of cells of the same type. !n the a#ove program* we have array x of type int of si5 elements. )e can only store integers in this array. )e cannot put int in first location* float in second location and double in third location. )hat is x9 x is a name of collection of items. !ts individual items are num#ered from -ero to one less than array si-e. To access a cell* use the array name and an inde5 as under0 5H0I* 5H1I* 5H$I* 5H3I* 5H=I* 5H I To manipulate the first element* we will use the inde5 -ero as x[0] and so on. The arrays look like in the memory as follows0

Page B of 103

Elementary Data Structures

PH0I 'rray cells are contiguous in computer memory PH1I PH$I PH3I PH=I PH I 'rray occupies contiguous memory area in the computer. !n case of the a#ove e5ample* if some location is assigned to x[0] * the ne5t location can not contain data other than x[1] . The computer memory can #e thought of as an array. !t is a very #ig array. Suppose a computer has memory of $:>* you can think it as an array of si-e $ million and the si-e of each item is 3$ #its. +ou must have studied in detail a#out it in the computer organi-ation* and 'ssem#ly language courses. !n this array* we will put our programs* data and other things. !n the a#ove program* we have declared an array named x. Mx4 is an array4s name #ut there is no varia#le x. Mx4 is not an lvalue. !f some varia#le can #e written on the left2 hand side of an assignment statement* this is lvalue varia#le. !t means it has some memory associated with it and some value can #e assigned to it. /or e5ample* if we have the code int a, b; it can #e written as b = 2; it means that put $ in the memory location named b. )e can also write as a = b; it means whatever b has assign it to a* that is a copy operation. !f we write as a = 5; it means put the num#er in the memory location which is named as a. >ut we cannot write 2 = a; that is to put at num#er $ what ever the value of a is. )hy can4t we do that9 Aum#er $ is a constant. !f we allow assignment to constants what will happen9 Suppose Ma4 has the value num#er 3. Aow we assigned num#er $ the num#er 3 i.e. all the num#er $ will #ecome num#er 3 and the result of 2 + 2 will #ecome B. Therefore it is not allowed. Mx4 is a name of array and not an lvalue. So it cannot #e used on the left hand side in an assignment statement. &onsider the following statements int 5HBIC int nC 5H0I J C 5H1I J $C 5 J 3C NNnot allowed 5 J a , #C NN not allowed 5 J OnC NN not allowed !n the a#ove code snippet* we have declared an array x of int. Aow we can assign values to the elements of x as x[0] = 5 or x[1] = 2 and so on. The last three statements are not allowed. )hat does the statement x = 3; mean9 's x is a name of array and this statement is not clear* what we are trying to do here9 're we trying to

Page D of 103

Elementary Data Structures assign 3 to each element of the array9 This statement is not clear. ?esultantly* it can not #e allowed. The statement x = a + b is also not allowed. There is nothing wrong with a + b. >ut we cannot assign the sum of values of a and b to x. !n the statement x = &n* we are trying to assign the memory address of n to x which is not allowed. The reason is the name x is not lvalue and we cannot assign any value to it. /or understanding purposes* consider x as a constant. !ts name or memory location can not #e changed. This is a collective name for si5 locations. )e can access these locations as x[0], x[1] up to x[5] . This is the way arrays are manipulated. Sometimes* you would like to use an array data structure #ut may lack the information a#out the si-e of the array at compile time. Take the e5ample of telephone directory. +ou have to store one lakh 1100*0003 names in an array. >ut you never know that the num#er of entries may get dou#le or decline in future. Similarly* you can not say that the total population of the country is one crore 110 million3 and declare an array of one crore names. +ou can use one lakh locations now and remaining will #e used as the need arrives. >ut this is not a good way of using the computer resources. +ou have declared a very #ig array while using a very small chunk of it. Thus the remaining space goes waste which can* otherwise* #e used #y some other programs. )e will see what can #e the possi#le solution of this pro#lem9 Suppose you need an integer array of si-e n after the e5ecution of the program. )e have studied that if it is known at the e5ecution of the program that an array of si-e $0 or 30 is needed* it is allocated dynamically. The programming statement is as follows0 intF y J new intH$0IC !t means we are re.uesting computer to find twenty memory locations. 8n finding it* the computer will give the address of first location to the programmer which will #e stored in y. 'rrays locations are contiguous i.e. these are ad"acent. These twenty locations will #e contiguous* meaning that they will #e neigh#ors to each other. Aow y has #ecome an array and we can say y[0] =1 or y[5] = 15. 7ere y is an lvalue. >eing a pointer* it is a varia#le where we can store the address of some varia#le. )hen we said int* y = ne int[20]; the new returns the memory address of first of the twenty locations and we store that address into y. 's y is a pointer varia#le so it can #e used on the left2hand side. )e can write it as0 y J O5H0IC !n the a#ove statement* we get the address of the fist location of the array x and store it in y. 's y is lvalue, so it can #e used on left hand side. This means that the a#ove statement is correct. y J 5C Similarly* the statement y = x is also correct. x is an array of si5 elements that holds the address of the first element. >ut we cannot change this address. 7owever we can get that address and store it in some other varia#le. 's y is a pointer varia#le and lvalue so the a#ove operation is legal. )e have dynamically allocated the memory for the array. This memory* after the use* can #e released so that other programs can use Page Q of 103

Elementary Data Structures it. )e can use the delete keyword to release the memory. The synta5 is0 deleteH I yC )e are releasing the memory* making it availa#le for use #y other programs. )e will not do it in case of x array* as Mnew4 was not used for its creation. So it is not our responsi#ility to delete x.

List data structure


The !i"t data structure is among the most generic of data structures. !n daily life* we use shopping list* groceries list* list of people to invite to a dinner* list of presents to give etc. !n this course* we will see how we use lists in programming. ' list is the collection of items of the same type 1grocery items* integers* names3. The data in arrays are also of same type. )hen we say int x[6]; it means that only the integers can #e stored in it. The same is true for list. The data which we store in list should #e of same nature. The items* or elements of the list* are stored in some particular order. )hat does this mean9 Suppose in the list* you have the fruit first which are also in some order. +ou may have names in some alpha#etical order i.e. the names which starts with # should come first followed #y the name starting with $ and so on. The order will #e reserved when you enter data in the list. !t is possi#le to insert new elements at various positions in the list and remove any element of the list. +ou have done the same thing while dealing with arrays. +ou enter the data in the array* delete data from the array. Sometimes the array si-e grows and at times* it is reduced. )e will do this with the lists too. (ist is a set of elements in a linear order. Suppose we have four names a1, a2, a3, a% and their order is as &a3, a1, a2, a%' i.e. a3* is the first element* a1 is the second element* and so on. )e want to maintain that order in the list when data is stored in the list. )e don4t want to distur# this order. The order is important hereC this is not "ust a random collection of elements #ut an ordered one. Sometimes* this order is due to sorting i.e. the things that start with # come first. 't occasions* the order may #e due to the importance of the data items. )e will discuss this in detail while dealing with the e5amples. Aow we will see what kind of operations a programmer performs with a list data structure. /ollowing long list of operations may help you understand the things in a comprehensive manner. Operation Name create(ist13 copy13 clear13C insert1P* 93 remove193 get193 update1P* 93 Description &reate a new list 1presuma#ly empty3 Set one list to #e a copy of another &lear a list 1remove all elements3 !nsert element P at a particular position in the list ?emove element at some position in the list %et element at a given position ?eplace the element at a given position with P

Page R of 103

Elementary Data Structures find1P3 length13 Determine if the element P is in the list ?eturns the length of the list.

(reate!i"t&' is a function which creates a new list. /or e5ample to create an array* we use int x[6] or int* y = ne int[20]; we need similar functionality in lists too. The (o)y&' function will create a copy of a list. The function (lear&' will remove all the elements from a list. )e want to insert a new element in the list* we also have to tell where to put it in the list. /or this purpose in"ert&*, )o"ition' function is used. Similarly the function re+ove&)o"ition' will remove the element at position. To get an element from the list ,et&)o"ition' function is used which will return the element at position. To replace an element in the list at some position the function u)date&*, )o"ition' is used. The function find&*' will search * in the list. The function len,t-&' tells us a#out the num#er of elements in the list. )e need to know what is meant #y ;particular position< we have used ;9< for this in the a#ove ta#le. There are two possi#ilities0 6se the actual inde5 of element0 i.e. insert it after element 3* get element num#er B. This approach is used with arrays 6se a ;current< marker or pointer to refer to a particular position in the list. The first option is used in the data structures like arrays. )hen we have to manipulate the arrays* we use inde5 like x[3], x[6] . !n the second option we do not use first* second etc for position #ut say wherever is the current pointer. Sust think of a pointer in the list that we can move forward or #ackward. )hen we say get* insert or update while using the current pointer* it means that wherever is the current pointer* get data from that position* insert data after that position or update the data at that position. !n this case* we need not to use num#ers. >ut it is our responsi#ility that current pointer is used in a proper way. !f we use the ;current< marker* the following four methods would #e useful0 Functions Description start13 :oves the ;current< pointer to the very first element tail13 :oves the ;current< pointer to the very last element ne5t13 :ove the current position forward one element #ack13 :ove the current position #ackward one element !n the ne5t lecture* we will discuss the implementation of the list data structure and write the functions discussed today* in &,, language.

Page 10 of 103

Elementary Data Structures

Lecture No. 02
Summary
13 (ist !mplementation add :ethod next :ethod re+ove :ethod find :ethod 8ther :ethods 'nalysis 8f 'rray (ist (ist 6sing (inked :emory (inked (ist

$3 33 =3

Today* we will discuss the concept of list operations. +ou may have a fair idea of M "tart operation4 that sets the current pointer to the first element of the list while the tail operation moves the current pointer to the last element of the list. !n the previous lecture* we discussed the operation next that moves the current pointer one element forward. Similarly* there is the Mba(. operation4 which moves the current pointer one element #ackward.

List Implementation
Aow we will see what the implementation of the list is and how one can create a list in &,,. 'fter designing the interface for the list* it is advisa#le to know how to implement that interface. Suppose we want to create a list of integers. /or this purpose* the methods of the list can #e implemented with the use of an array inside. /or e5ample* the list of integers 1$* B* Q* D* 13 can #e represented in the following manner where the current position is 3. A $ B Q D 1 current si e

Page 11 of 103

Elementary Data Structures 1 $ 3 = ! "

!n this case* we start the inde5 of the array from 1 "ust for simplification against the usual practice in which the inde5 of an array starts from -ero in &,,. !t is not necessary to always start the inde5ing from -ero. Sometimes* it is re.uired to start the inde5ing from 1. /or this* we leave the -eroth position and start using the array from inde5 1 that is actually the second position. Suppose we have to store the num#ers from 1 to B in the array. )e take an array of D elements and put the num#ers from the inde5 1. Thus there is a correspondence #etween inde5 and the num#ers stored in it. This is not very useful. So* it does not "ustify the non2use of -eroth position of the array out2rightly. 7owever for simplification purposes* it is good to use the inde5 from 1. add Method Aow we will talk a#out adding an element to the list. Suppose there is a call to add an element in the list i.e. add&/'. 's we said earlier that the current position is 3* so #y adding the element R to the list* the new list will #e 1$* B* Q* R* D* 13. To add the new element 1R3 to the list at the current position* at first* we have to make space for this element. /or this purpose* we shift every element on the right of Q 1the current position3 to one place on the right. Thus after creating the space for new element at position =* the array can #e represented as A $ 1 B $ Q 3 = D 1 current ! si e "

Aow in the second step* we put the element R at the empty space i.e. position =. Thus the array will attain the following shape. The figure shows the elements in the array in the same order as stored in the list. A $ 1 B $ Q 3 R = D 1 B current # si e $

)e have moved the current position to = while increasing the si-e to B. The si-e shows that the elements in the list. )here as the si-e of the array is different that we have defined already to a fi5ed length* which may #e 100* $00 or even greater. next Method Aow let4s see another method* called Mnext0. )e have talked that the ne5t method moves the current position one position forward. !n this method* we do not add a new element to the list #ut simply move the pointer one element ahead. This method is re.uired while employing the list in our program and manipulating it according to the re.uirement. There is also an array to store the list in it. )e also have two varia#les2 (urrent and "i1e to store the position of current pointer and the num#er of elements in the list. >y looking on the values of these varia#les* we can find the state of the list i.e. how many elements are in the list and at what position the current pointer is. The method next is used to know a#out the #oundary conditions of the list i.e. the array #eing used #y us to implement the list. To understand the #oundary conditions*

Page 1$ of 103

Elementary Data Structures we can take the e5ample of an array of si-e 100 to implement the list. 7ere* 100 elements are added to the array. (et4s see what happens when we want to add 101st element to the array9 )e used to move the current position #y next method and reached the 100th position. Aow* in case of moving the pointer to the ne5t position 1i.e. 101st3* there will #e an error as the si-e of the array is 100* having no position after this point. Similarly if we move the pointer #ackward and reach at the first position regardless that the inde5 is 0 or 1. >ut what will happen if we want to move #ackward from the first position9 These situations are known as #oundary conditions and need attention during the process of writing programs when we write the code to use the list. )e will take care of these things while implementing the list in &,, programs. remove Method )e have seen that the add method adds an element in the list. Aow we are going to discuss the re+ove method. The re+ove method removes the element residing at the current position. The removal of the element will #e carried out as follows. Suppose there are B elements 1$* B* Q* R* D* 13 in the list. The current pointer is pointing to the position that has the value D. )e remove the element* making the current position empty. The si-e of the list will #ecome . This is represented in the following figure.

$ 1

B $

Q 3

R =

1 B

current "

si e $ "

)e fill in the #lank position left #y the removal of D #y shifting the values on the right of position to the left #y one space. This means that we shift the remaining elements on the right hand side of the current position one place to the left so that the element ne5t to the removed element 1i.e. 13 takes its place 1the fifth position3 and #ecomes the current position element. )e do not change the current pointer that is still pointing to the position . Thus the current pointer remains pointing to the position despite the fact that there is now element 1 at this place instead of D. Thus in the re+ove method* when we remove an element* the element ne5t to it on the right hand side comes at its place and the remaining are also shifted one place to the right. This step is represented #y the following figure.

$ 1

B $

Q 3

R =

current "

si e "

f nd Method Aow lets talk a#out a function* used to find a specific element in the array. The find &x' function is used to find a specific element in the array. )e pass the element* which is to #e found* as an argument to the find function. This function then traverses the array until the specific element is found. !f the element is found* this function sets the current position to it and returns 1 i.e. true. 8n the other hand* if the element is not found* the function returns 0 i.e. false. This indicates that the element was not found.

Page 13 of 103

Elementary Data Structures /ollowing is the code of this find&x' function in &,,. int find 1int 53 G int " C for 1" J 1C " K si-e , 1C ",, 3 if 1'H"I JJ 5 3 #reak C if 1 " K si-e , 13 G current J " C return 1 C L return 0 C L

NN 5 is found NNcurrent points to the position where 5 found NN return true NNreturn false* 5 is not found

!n the a#ove code* we e5ecute a for loop to traverse the array. The num#er of e5ecution of this loop is e.ual to the si-e of the list. This for loop gets terminated when the value of loop varia#le 123 increases from the si-e of the list. 7owever we terminate the loop with the brea. statement if the element is found at a position. )hen the control comes out from the loop* we check the value of 2. !f the value of 2 is less than the si-e of the array* it means that the loop was terminated #y the brea. statement. )e use the brea. statement when we find the re.uired element 153 in the list. The e5ecution of brea. statement shows that the re.uired element was found at the position e.ual to the value of 2. So the program sets the (urrent position to 2 and comes out the function #y returning 1 1i.e. true3. !f the value of 2 is greater than the si-e of the array* it means that the whole array has traversed and the re.uired element is not found. So we simply return 0 1i.e. false3 and come out of the function. !ther Method" There are some other methods to implement the list using an array. These methods are very simple* which perform their task "ust in one step 1i.e. in one statement3. There is a ,et&' method * used to get the element from the current position in the array. The synta5 of this function is of one line and is as under return 'HcurrentI C This statement returns the element to which the (urrent is pointing to 1i.e. the current position3 in the list '. 'nother function is u)date&x'. This method is used to change 1set3 the value at the current position. ' value is passed to this method as an argument. !t puts that value at the current position. The following statement in this method carries out this process. ' HcurrentI J 5 C Then there is a method len,t-& '.This method returns the si-e of the list. The synta5 of this method is return si-e C

Page 1= of 103

Elementary Data Structures +ou may notice here that we are returning the si-e of the list and not the si-e of the array #eing used internally to implement the list. This "i1e is the num#er of the elements of the list* stored in the array. The ba(.&' method decreases the value of varia#le (urrent #y 1. !n other words* it moves the current position one element #ackward. This is done #y writing the statement. current 22 C The 22 is a decrement operator in &,, that decreases the value of the operand #y one. The a#ove statement can also #e written as current J current 21 C The "tart&' method sets the current position to the first element of the list. )e know that the inde5 of the array starts from 0 #ut we use the inde5 1 for the starting position. )e do not use the inde5 -ero. So we set the current position to the first element #y writing current J 1 C Similarly* the end&' method sets the current position to the last element of the list i.e. "i1e. So we write current J si-e C

Analysis of Array List


Aow we analy-e the implementation of the list while using an array internally. )e analy-e different methods used for the implementation of the list. )e try to see the level upto which these are efficient in terms of &P64s time consumption. Time is the ma"or factor to see the efficiency of a program. Add /irst of all* we have talked a#out the add method. )hen we add an element to the list* every element is moved to the right of the current position to make space for the new element. So* if the current position is the start of the list and we want to add an element in the #eginning* we have to shift all the elements of the list to the right one place. This is the worst case of adding an element to the list. Suppose if the si-e of the list is 10000 or $0000* we have to do the shift operation for all of these 10000 or $0000 elements. Aormally* it is done #y shifting of elements with the use of a for loop. This operation takes much time of the &P6 and thus it is not a good practice to add an element at the #eginning of a list. 8n the other hand* if we add an element at the end of the list* it can #e done #y carrying out Mno shift operation4. !t is the #est case of adding an element to the list. 7owever* normally we may have to move half of the elements. The usage of add method is the matter warranting special care at the time of implementation of the list in our program. To provide the interface of the list* we "ust define these methods.

Page 1 of 103

Elementary Data Structures Remove )hen we remove an element at the current position in the list* its space gets empty. The current pointer remains at the same position. To fill this space* we shift the elements on the right of this empty space one place to the left. !f we remove an element from the #eginning of the list* then we have to shift the entire remaining elements one place to the left. Suppose there is a large num#er of elements* say 10000 or $0000* in the list. )e remove the first element from the list. Aow to fill this space* the remaining elements are shifted 1that is a large num#er3. Shifting such a large num#er of elements is time consuming process. The &P6 takes time to e5ecute the for loop that performs this shift operation. Thus to remove an element at the #eginning of the list is the worst case of re+ove method. 7owever it is very easy to remove an element at the end of the list. !n average cases of the re+ove method we e5pect to shift half of the elements. This average does not mean that in most of the cases* you will have to shift half the elements. !t is "ust the average. )e may have to shift all the elements in one operation 1if we remove at the #eginning3 and in the second operation* we have to shift no element 1if we remove at the end3. Similarly* in certain operations* we have to shift "ust 10* 1 elements. # nd )e have discussed that the find method takes an element and traverses the list to find that element. The worst case of the find method is that it has to search the entire list from #eginning to end. So* it finds the element at the end of the array or the element is not found. 8n average the find method searches at most half the list. The other methods get 13* length 13 etc are one2step methods. They carry out their operation in one instruction. There is no need of any loop or other programming structures to perform the task. The ,et&' method gets the value from the specified position "ust in one step. Similarly the u)date&' method sets a value at the specific position "ust in one2step. The length 13 method returns the value of the si-e of the list. The other methods ba(.&', "tart&' and end&' also perform their tasks only in one step.

List using Linked Memory


)e have seen the implementation of the list with the use of an array. Aow we will discuss the implementation of the list while using linked memory. !n an array* the memory cells of the array are linked with each other. !t means that the memory of the array is contiguous. !n an array* it is impossi#le that one element of the array is located at a memory location while the other element is located somewhere far from it in the memory. !t is located in very ne5t location in the memory. !t is a property of the array that its elements are placed together with one another in the memory. :oreover* when we have declared the si-e of the array* it is not possi#le to increase or decrease it during the e5ecution of the program. !f we need more elements to store in the array* there is need of changing its si-e in the declaration. )e have to compile the program again #efore e5ecuting it. Aow array will #e of the new si-e. >ut what happens if we again need to store more elements9 )e will change the code of our program to change the declaration of the array while recompiling it. Suppose we have used the dynamic memory allocation and created an array of 100 elements with the use of ne operator. !n case of need of $00 elements* we will release this array and allocate a new array of $00 elements. >efore releasing the Page 1B of 103

Elementary Data Structures previous array* it will wise to copy its elements to the new array so that it does not lose any information. Aow this new array is in Mready for use4 position. Thus the procedure of creating a new array is not an easy task. To avoid such pro#lems* usually faced #y the programmers while using an array* there is need of using linked memory in which the various cells of memory* are not located continuously. !n this process* each cell of the memory not only contains the value of the element #ut also the information where the ne5t element of the list is residing in the memory. !t is not necessary that the ne5t element is at the ne5t location in the memory. !t may #e anywhere in the memory. )e have to keep a track of it. Thus* in this way* the first element must e5plicitly have the information a#out the location of the second element. Similarly* the second element must know where the third element is located and the third should know the position of the fourth element and so on. Thus* each cell 1space3 of the list will provide the value of the element along with the information a#out where the ne5t element is in the memory. This information of the ne5t element is accomplished #y holding the memory address of the ne5t element. The memory address can #e understood as the inde5 of the array. 's in case of an array* we can access an element in the array #y its inde5. Similarly* we can access a memory location #y using its address* normally called memory address.

Linked List
/or the utili-ation of the concept of linked memory* we usually define a structure* called linked list. To form a linked list* at first* we define a node. ' node comprises two fields. i.e. the ob2e(t field that holds the actual list element and the next that holds the starting location of the ne5t node.

o%&ect

ne't

' chain of these nodes forms a linked list. Aow let4s consider our previous list* used with an array i.e. $* B* Q* D* 1. /ollowing is the figure which represents the list stored as a linked list. (ead

si e - "

current This diagram "ust represents the linked list. !n the memory* different nodes may occur at different locations #ut the next part of each node contains the address of the ne5t node. Thus it forms a chain of nodes which we call a linked list. )hile using an array we knew that the array started from inde5 1that means the first element of the list is at inde5 1. Similarly in the linked list we need to know the starting point of the list. /or this purpose* we have a pointer -ead that points to the Page 1D of 103

Elementary Data Structures first node of the list. !f we don4t use -ead* it will not #e possi#le to know the starting position of the list. )e also have a pointer (urrent to point to the current node of the list. )e need this pointer to add or remove current node from the list. 7ere in the linked list* the (urrent is a pointer and not an inde5 as we used while using an array. The next field of the last node points to nothing .!t is the end of the list. )e place the memory address A6(( in the last node. A6(( is an invalid address and is inaccessi#le. Aow again consider the list $* B* Q* D* 1. The previous figure represents this list as a linked list. !n this linked list* the -ead points to $* $ points to B* B points to Q* Q points to D and D points to 1. :oreover we have the current position at element Q. This linked list is stored in the memory. The following diagram depicts the process through which this linked list is stored in the memory.

Page 1Q of 103

Elementary Data Structures

,.", ,.") current ,."! ,."# ,."" ,."$ ,."+ ,."* ,."/ ,.$. ,.$, head ,.$) ,.$! ,.$# ,.$"

$ ,.$! ) ,.", + ,.$. , . ,."# * ,."+

)e can see in the figure that each memory location has an address. Aormally in programming* we access the memory locations #y some varia#le names. These varia#le names are alias for these locations and are like la#els that are put to these memory locations. )e use -ead and (urrent varia#le names instead of using the memory address in num#ers for starting and the current nodes. !n the figure* we see that -ead is the name of the memory location 10B$ and the name (urrent is used for the memory address 10 3. The -ead holds the address 10 = and the element $* the first one in the list* is stored in the location 10 =. Similarly (urrent holds the address 10B3 where the element Q is stored which is our current position in the list. !n the diagram* two memory locations comprise a node. So we see that the location 10 = holds the element $ while the ne5t location 10 holds the address of the memory location 110 13 where the ne5t element of the list 1i.e. B3 is stored. Similarly the next part of the node that has value B holds the memory address of the location occupied #y the ne5t element 1i.e. Q3 of the list. The other nodes are structured in a similar fashion. Thus* #y knowing the address of the ne5t element we can traverse the whole list.

Page 1R of 103

Elementary Data Structures

Lecture No. 0$
Summary
(inked (ist inside &omputer :emory (inked (ist 8perations (inked (ist 6sing &,, E5ample Program

!n the previous lectures* we used an array to construct a list data structure and o#served the limitation that array #eing of fi5ed si-e can only store a fi5ed num#er of elements. Therefore* no more elements can #e stored after the si-e of the array is reached. !n order to resolve this* we adopted a new data structure called lin.ed li"t. )e started discussing* how linked lists are stored in computer memory and how memory chains are formed.

L n%ed L "t !&erat on"


The linked list data structure provides operations to work on the nodes inside the list. The first operation we are going to discuss here is to create a new node in the memory. The #dd&/' is used to create a new node in the memory at the current position to hold M/4. +ou must remem#er while working with arrays* to add an element at the current position that all the elements after the current position were shifted to the right and then the element was added to the empty slot. 7ere* we are talking a#out the internal representation of the list using linked list. !ts interfa(e will remain the same as in case of arrays. )e can create a new node in the following manner in the add&' operation of the linked list with code in &,,0 3ode * ne 3ode = ne 3ode&/'; The first part of the statement that is on the left of the assignment is declaring a varia#le pointer of type 3ode. !t may also #e written as 3ode * ne 3ode. 8n the right of this statement* the ne operator is used to create a new 3ode o#"ect as ne 3ode&/'. This is one way in &,, to create o#"ects of classes. The name of the class is provided with the ne operator that causes the constructor of the class to #e called. The constructor of a class has the same name as the class and as this a function* parameters can also #e passed to it. !n this case* the constructor of the 3ode class is called and M/4 is passed to it as an int parameter. 7ence* the whole statement means0 ;&all the constructor of the 3ode class and pass it M/4 as a parameter. 'fter

Page $0 of 103

Elementary Data Structures constructing the o#"ect in memory* give me the starting memory address of the o#"ect. That address will #e stored in the pointer varia#le ne 3ode.< To create an o#"ect of int type in the same manner* we can write as0 int * i = ne int ; Previously* we used the same techni.ue to allocate memory for an array of ints as0 int * i = ne int [10] ; Aow after the node has #een created* how the node is fit into the chain of the linked list. Fig )0 Insertion of ne1 Node into the lin2ed list $ B Q D 1

current 3 R newAode

!n the a#ove figure* there is a linked list that contains five nodes with data elements as 2* 6* 4* 5 and 1. The (urrent pointer is pointing to the node with element as 4. )e want to insert a new node with data element /. This new node will #e inserted at the current position 1the position where the (urrent pointer is pointing to3. This insertion operation is performed in a step #y step fashion. 2 The first step is to point ne5t pointer of the new node 1with data element as /3 to the node with data element as 5. 2 The second step is to point the ne5t pointer of the node with data element 4 to the node the new node with data element /. 2 The third step is to change the (urrent pointer to point to the new node. Aow* the updated linked list has nodes with data elements as 2* 6* 4* /* 5 and 1. The list si-e has #ecome B.

L n%ed L "t U" n' C((


6* 7-e 3ode (la"" *6 class Aode G pu#lic0 int get13 G return o#"ectC LC void set1int o#"ect3 G this2To#"ect J o#"ectC LC

Page $1 of 103

Elementary Data Structures Aode F getAe5t13 G return ne5tAodeC LC void setAe5t1Aode F ne5tAode3 G this2Tne5tAode J ne5tAodeC LC private0 int o#"ectC Aode F ne5tAodeC LC

)henever* we write a class* it #egins with the word (la"" followed #y the (la""8na+e and the #ody of the class enclosed within curly #races. !n the #ody* we write its )ubli( varia#les* methods and then )rivate varia#les and methods* this is normally the se.uence. !f there is no code to write inside the constructor function of a class* we need not to declare it ourselves as the compiler automatically creates a default constructor for us. Similarly* if there is nothing to #e done #y the destructor of the class* it will #e #etter not to write it e5plicitly. ?ather* the compiler writes it automatically. ?emem#er* the default constructor and destructor do nothing as these are the function without any code statements inside. (et4s start with the data mem#ers first. These are given at the #ottom of the class #ody with the scope mentioned as )rivate. These data mem#ers are actually two parts of a linked list4s node. /irst varia#le is ob2e(t of type int* present there to store the data part of the node. The second varia#le is next3ode* which is a pointer to an o#"ect of type 3ode. !t has the address of the ne5t element of the linked list. The very first )ubli( function given at the top is ,et&'. )e have written its code within the class 3ode. 9t returns #ack the value of the varia#le ob2e(t i.e. of the type of int. )hen we write class in &,,* normally* we make two files 1.- and .())3 for a class. The .- file contains the declarations of )ubli( and )rivate mem#ers of that class. The )ubli( methods are essentially the interface of the class to #e employed #y the users of this class. The .()) file contains the implementation for the class methods that has the actual code. This is usually the way that we write two files for one class. >ut this is not mandatory. !n the code given a#ove* we have only one file .()), instead of separating into two files. 's the class methods are very small* so their code is written within the #ody of the class. This facilitates us in carrying on discussion. Thus instead of talking a#out two files* we will only refer to one file. 8n the other hand* compiler takes these functions differently that are called inline functions. The compiler replaces the code of these inline functions wherever the call to them is made. The second method in the a#ove2mentioned class is "et&' t-at accepts a parameter of type int while returning #ack nothing. The accepted parameter is assigned to the internal data mem#er ob2e(t. Aotice the use of t-i" pointer while assigning the value to the internal data mem#er. !t is used whenever an o#"ect wants to talk to its own mem#ers. The ne5t method is ,et3ext&' -i(- returns a pointer to an o#"ect of type 3ode lying somewhere in the memory. !t returns next3ode i.e. a pointer to an o#"ect of type 3ode. 's discussed a#ove* next3ode contains the address of ne5t node in the linked list. The last method of the class is "et3ext&' t-at accepts a pointer of type 3ode, further assigned to next3ode data mem#er of the o#"ect. This method is used to connect the ne5t node of the linked list with the current o#"ect. !t is passed an address of the ne5t Page $$ of 103

Elementary Data Structures node in the linked list. (et4s discuss a little #it a#out classes. ' very good analogy of a class is a factory. Think a#out a car factory. 8n the placement of order* it provides us with the num#er of vehicles we ordered for. Similarly* you can see num#er of other factories in your daily2life that manufacture the specific products. (et4s take this analogy in &,, language. Suppose* we want to make a factory in &,,. >y the way* what is our 3ode class9 !t is actually a factory that creates nodes. )hen we want to make a new node* a new operator is used. >y using ne operator with the 3ode class* actually* we send an order to 3ode factory* to make as many as nodes for us. So we have a good analogy* to think a#out a class as a factory. The products that are made #y the factory have their own characteristics. /or e5ample* a car made #y an automo#ile factory has an engine* wheels* steering and seats etc. These varia#les inside a class are called "tate variable". Aow the kinds of operations this car can do are the +et-od" of its class. ' car can #e driven* engine can #e started* gears can #e shifted and an accelerator can #e pressed to run it faster. Similarly* the Aode class creates nodes* where every node has two2state varia#les i.e. ob2e(t and next3ode. )e have already seen its operations in the a#ove code. )e use ne to create new o#"ect or an array of new o#"ects* stored in memory. (et4s see the code #elow. NF (ist class FN Uinclude Kstdli#.hT Uinclude VAode.cppV class (ist G pu#lic0 NN &onstructor (ist13 G headAode J new Aode13C headAode2TsetAe5t1A6((3C currentAode J A6((C si-e J 0C L

)e are creating a list factory here employed to create list o#"ects. ?emem#er the list operationsC add* re+ove* next* ba(. and "tart etc. (et4s see the a#ove class declaration code in detail. There are two in(lude "tate+ent" at the start. The first line is to include a standard li#rary "tdlib.- -ile t-e "e(ond line includes the 3ode class file 3ode.()). This 3ode class is used to create nodes that form a !i"t o#"ect. So this !i"t factory will order 3ode class to create new nodes. The (ist class itself carries out the chain management of these Aode o#"ects. )e have written our own constructor of !i"t class as the default constructor is not Page $3 of 103

Elementary Data Structures sufficient enough to serve the purpose. The !i"t constructor is parameterless. The very first step it is doing internally is that it is asking 3ode class to create a new node and assigning the starting address of the new 3ode4s o#"ect to the -ead3ode data mem#er. !n the second statement* we are calling "et3ext&3 method of the 3ode class for the o#"ect pointed to #y the -ead3ode pointer. This call is to set the next3ode data mem#er to 3:!!* i.e. 3ode4s o#"ect pointed to #y the -ead3ode pointer is not pointing to any further 3ode. The ne5t statement is to set the (urrent3ode pointer to 3:!!. So at the moment* we have initiali-ed the (urrent3ode pointer to 3:!! that is not pointing to any 3ode o#"ect. The ne5t statement is to initiali-e the "i1e data mem#er to 0 indicating that there is no node present in the list. 'll this processing is done inside the constructor of !i"t class* as we want all this done when a list o#"ect is created. &onsidering the analogy of car factory* the constructor function can perform certain tasks0 The oil is poured into the engine* the tyres are filled2in with air etc. (et4s see the add method of the !i"t class0 NF add13 class method FN void add 1int add8#"ect3 G 1. Aode F newAode J new Aode13C $. newAode2Tset1add8#"ect3C 3. if1 currentAode WJ A6(( 3 =. G . newAode2TsetAe5t1currentAode2TgetAe5t133C B. currentAode2TsetAe5t1 newAode 3C D. last&urrentAode J currentAodeC Q. currentAode J newAodeC R. L 10. else 11. G 1$. newAode2TsetAe5t1A6((3C 13. headAode2TsetAe5t1newAode3C 1=. last&urrentAode J headAodeC 1 . currentAode J newAodeC 1B. L 1D. si-e ,,C L

The interface or signatures of add&' method is similar to the one discussed in case of an array. This method takes the o#"ect to #e added as a parameter. The implementation of this add&' method is a #it longer as the method is #eing implemented for linked list. !n the first statement* a new 3ode o#"ect is created with its address stored in the ne 3ode pointer varia#le. The second statement is to call "et&' method of the 3ode o#"ect pointed to #y the ne 3ode pointer. +ou can note the way the method is called. ' pointer varia#le is at the left most side then an arrow sign 12T3* then the name of the method with appropriate arguments within parenthesis. !t is followed #y the if2 statement that checks the (urrent3ode is not 3:!! to perform certain operations inside the if2code #lock. !nside the if2statement* at line * the next3ode pointer of the new node is #eing set to the next3ode of the o#"ect pointed to #y the (urrent3ode Page $= of 103

Elementary Data Structures pointer. !n order to understand the statements given in this code properly* consider the fig $ a#ove* where we added a node in the linked list. )e have done step 1 at line . 't line B* we are performing the second step #y setting the ne 3ode in the next3ode pointer of the o#"ect pointed to #y the (urrent3ode. 't line D* we are saving the current position 1address3 of the (urrent3ode pointer in the pointer varia#le la"t;urrent3ode* which might #e useful for #ackward traversing. 'lthough* the fig 1 1left part3 indicates movement in one direction from left to right #ut the la"t;urrent3ode pointer node can #e used #y the ba(.&' mem#er function to traverse one position #ack from right to left. 't line Q* the (urrent3ode pointer is assigned the address of the o#"ect pointed to #y ne 3ode. This way* a new node is added in already e5istent linked list. (ine 10 is start of the el"e part of if2statement. This is e5ecuted if the (urrent3ode is 3:!!. !t means that there is no node present in the list previously and first node is going to #e added. 't line 1$* we are setting the next3ode pointer of the o#"ect pointed to #y ne 3ode pointer. The next3ode is #eing set to 3:!! #y calling the "et3ext&' method. Then at line 13* we point the -ead pointer 1-ead3ode3 to this new node pointed to #y ne 3ode pointer. Aote that -ead3ode is pointing to a node that is there despite the fact that the "i1e of the linked list is 0. 'ctually* we have allocated a 3ode o#"ect for -ead3ode pointer. 'lthough* we don4t need a 3ode o#"ect here* yet it will #e helpful when we perform other operations like re+ove&' and find&'. 't line 1=* the -ead3ode address is #eing assigned to la"t;urrent3ode. 't line 1 * (urrent3ode pointer is assigned the address of ne 3ode. 't the end i.e. at line 1D* the "i1e of the list is incremented #y 1. List list3 headAode si e - .

currentAode list0add4)53 headAode last&urrentAode currentAode list0add4$53 si e - ) $ si e - ,

headAodee

last&urrentAode

/ig 3. 'dd operation of linked list /ollowing is the cru5 of this add&' operation 0 /irstly* it will make a new node #y calling Aode class constructor. !nsert the value e.g. $. of the node into the node #y calling the set method. Aow if the list already e5ists Page $ of 103

Elementary Data Structures 1has some elements inside or its si-e is non2-ero3* it will insert the node after the current position. !f the list does not already e5ist* this node is added as the first element inside the list. (et4s try to add few more elements into the a#ove linked list in the figure. The following are the lines of code to #e e5ecuted to add nodes with values 4* 5 and 1 into the linked list. list0add4*53 list0add4+53 list0add4,53 currentAode

si e - "

headAode /ig =. :ore Aodes added into linked list

last&urrentAode

Aow we will see the remaining methods of the linked list. The ,et&' method of the !i"t class is given #elow NF get13 class method FN int get13 G if 1currentAode WJ A6((3 return currentAode2Tget13C L This method firstly confirms that the (urrent3ode pointer is not 3:!!. !f it is not 3:!!, then it must #e pointing to some 3ode o#"ect as inside the constructor of the !i"t class* we have initiali-ed this pointer varia#le to 3:!!. That indicates that the (urrent3ode is 3:!! when there is no element inside the list. 7owever* when a 3ode o#"ect is added into it* it starts pointing to it. So* this ,et&' returns the address of the node pointed to #y the (urrent3ode pointer. /urther* we have another method given #elow0 NF ne5t13 class method FN #ool ne5t13 G 1. if 1currentAode JJ A6((3 return falseC $. 3. last&urrentAode J currentAodeC =. currentAode J currentAode2TgetAe5t13C . return trueC LC Page $B of 103

Elementary Data Structures

This is next13 method* used to advance the (urrent3ode pointer to the ne5t node inside the linked list. 't line 1* the (urrent3ode is #eing checked to confirm that there are some elements present in the list to advance further. 't line 1* the method is returning fal"e if there is no element present in the list. 't line 3* it is storing the value of the (urrent3ode pointer into the la"t;urrent3ode. 't line =* (urrent3ode is calling the ,et3ext&' method to get the address of ne5t node to #e stored in the (urrent3ode pointer to advance the (urrent3ode pointer to the ne5t element. 't line * it returns true indicating the method is successful in moving to the ne5t node.

Exam&)e *ro'ram
%iven #elow is the full source code of the e5ample program. +ou can copy* paste and compile it right away. !n order to understand the linked list concept fully* it is highly desira#le that you understand and practice with the #elow code. Uinclude Kiostream.hT Uinclude Kstdli#.hT NF The Aode class FN class Aode G pu#lic0 int get13 G return o#"ectC LC void set1int o#"ect3 G this2To#"ect J o#"ectC LC Aode F getAe5t13 G return ne5tAodeC LC void setAe5t1Aode F ne5tAode3 G this2Tne5tAode J ne5tAodeC LC private0 int o#"ectC Aode F ne5tAodeC LC NF The (ist class FN class (ist G pu#lic0 (ist13C void add 1int add8#"ect3C int get13C #ool ne5t13C friend void traverse1(ist list3C friend (ist addAodes13C private0 int si-eC Aode F headAodeC Aode F currentAodeC

Page $D of 103

Elementary Data Structures Aode F last&urrentAodeC LC NF &onstructor FN (ist00(ist13 G headAode J new Aode13C headAode2TsetAe5t1A6((3C currentAode J A6((C last&urrentAode J A6((C si-e J 0C L NF add13 class method FN void (ist00add 1int add8#"ect3 G Aode F newAode J new Aode13C newAode2Tset1add8#"ect3C if1 currentAode WJ A6(( 3 G newAode2TsetAe5t1currentAode2TgetAe5t133C currentAode2TsetAe5t1 newAode 3C last&urrentAode J currentAodeC currentAode J newAodeC L else G newAode2TsetAe5t1A6((3C headAode2TsetAe5t1newAode3C last&urrentAode J headAodeC currentAode J newAodeC L si-e ,,C L NF get13 class method FN int (ist00get13 G if 1currentAode WJ A6((3 return currentAode2Tget13C L NF ne5t13 class method FN #ool (ist00ne5t13 G if 1currentAode JJ A6((3 return falseC last&urrentAode J currentAodeC currentAode J currentAode2TgetAe5t13C Page $Q of 103

Elementary Data Structures if 1currentAode JJ A6(( XX si-e JJ 03 return falseC else return trueC L NF /riend function to traverse linked list FN void traverse1(ist list3 G AodeF saved&urrentAode J list.currentAodeC list.currentAode J list.headAodeC for1int i J 1C list.ne5t13C i,,3 G cout KK VYn Element V KK i KK V V KK list.get13C L list.currentAode J saved&urrentAodeC L NF /riend function to add Aodes into the list FN (ist addAodes13 G (ist listC list.add1$3C list.add1B3C list.add1Q3C list.add1D3C list.add113C cout KK VYn (ist si-e J V KK list.si-e KKEYnEC return listC L main13 G (ist list J addAodes13C traverse1list3C L

The output of the e5ample program is as follows0 (ist si-e J Element Element Element Element Element 1 $ 3 = $ B Q D 1

Page $R of 103

Elementary Data Structures

Lecture No. 0+
Summary
:ethods of (inked (ist E5ample of list usage 'nalysis of (ink (ist Dou#ly2linked (ist &ircularly2linked lists Sosephus Pro#lem

Method" of L n%ed L "t


!n the previous lecture* we discussed the methods of linked list. These methods form the interface of the link list. /or further elucidation of these techni.ues* we will talk a#out the "tart method that has the following code. NN position currentAode and last&urrentAode at first element void start13 G last&urrentAode J headAodeC currentAode J headAodeC LC There are two statements in this method. )e assign the value of -ead3ode to #oth la"t;urrent3ode and (urrent3ode. These two pointers point at different nodes of the list. 7ere we have pointed #oth of these pointers at the start of the list. 8n calling some other method like next, these pointers will move forward. 's we can move in the singly2linked list in one direction* these pointers cannot go #ehind -ead3ode. )e will now see how a node can #e removed from the link list. )e use the method re+ove for this purpose. void remove13 G if1 currentAode WJ A6(( OO currentAode WJ headAode3 G 1step 13 last&urrentAode2TsetAe5t1currentAode2TgetAe5t133C 1step $3 delete currentAodeC 1step 33 currentAode J last&urrentAode2TgetAe5t13C 1step =3 si-e22C L LC

Page 30 of 103

Elementary Data Structures currentAode headAode $ last&urrentAode Suppose that the (urrent3ode is pointing at the location that contains the value B. ' re.uest for the removal of the node is made. ?esultantly* the node pointed #y (urrent3ode should #e removed. /or this purpose* at first* the next pointer of the node with value $ 1the node pointed #y the la"t;urrent3ode pointer3* that is #efore the node with value B* #ypasses the node with value B. !t is* now pointing to the node with value Q. The code of the first step is as0 last&urrentAode2TsetAe5t1currentAode2TgetAe5t133C )hat does the statement (urrent3ode8<,et3ext&' do9 The (urrent3ode is pointing to the node with value B while the next of this node is pointing to the node with value Q. That is the next pointer of node with value B contains the address of the node with value Q. The statement la"t;urrent3ode8<"et3ext&(urrent3ode8<,et3ext&'' will set the next pointer of the node pointed #y the la"t;urrent3ode to the node with value Q. So the next pointer of the node with value $ is pointing to the node with value Q. currentAode headAode Step1 $ last&urrentAode B Q D 1 Si-e J B Q D 1 Si-e J

+ou see that the ne5t pointer of the node having data element $ contains the address of the node having data element Q. The node with value B has #een disconnected from the chain while the node with value $ is connected to the node with the value Q. The code of the ne5t step is0 delete currentAodeC +ou already know* in case of allocation of the memory with the help of the ne keyword* the delete statement releases this memory which returns the memory to the system. Pictorially it can #e represented as0

Page 31 of 103

Elementary Data Structures

currentAode headAode Step1 $ Step$ last&urrentAode Q D 1 Si-e J

!n the ne5t step* we have moved the (urrent3ode to point the ne5t node. The code is0 currentAode J last&urrentAode2TgetAe5t13C !n the fourth step* the si-e of the list has #een reduced #y 1 after the deletion of one node i.e. si-e22C Step3 currentAode headAode Step1 $ Step$ last&urrentAode Q D 1 Step= Si-e J =

The ne5t method is len,t-&' that simply returns the si-e of the list. The code is as follows0 NN returns the si-e of the list int length13 G return si-eC LC The private data mem#ers of the list are0 private0 int si-eC NN contains the si-e of the list Aode FheadAodeC NN points to the first node of the list Aode FcurrentAode* NN current node Aode Flast&urrentAodeC NN last current node

Page 3$ of 103

Elementary Data Structures The list class completed "ust now* can #e termed as list factory. )e have included all the re.uired methods in it. )e may employ more methods if re.uired. ' programmer can get the si-e of the list* add or remove nodes in it #esides moving the pointers.

Exam&)e of ) "t u"a'e


Aow let4s see how we use the link list. 7ere is an e5ample showing the use of list0 NF ' simple e5ample showing the use of link list FN Uinclude KiostreamT Uinclude Kstdli#.hT Uinclude V(ist.cppV NN This contains the definition of (ist class NN main method int main1int argc* char FargvHI3 G (ist listC NN creating a list o#"ect NN adding values to the list list.add1 3C list.add1133C list.add1=3C list.add1Q3C list.add1$=3C list.add1=Q3C list.add11$3C NN calling the start method of the list list.start13C NN printing all the elements of the list while 1list.ne5t133 cout KK V(ist Element0 VKK list.get13KKendlC L The output of the program is0 (ist Element0 (ist Element0 13 (ist Element0 = (ist Element0 Q (ist Element0 $= (ist Element0 =Q (ist Element0 1$ (et4s discuss the code of the a#ove program. )e have included the standard li#raries #esides having the ;(ist.cpp< file. 6sually we do not include .cpp files. ?ather* the .h

Page 33 of 103

Elementary Data Structures files are included. )henever you write a class* two files will #e created i.e. .h 1header file containing the interface of the class3 and .cpp 1implementation file3. 7ere for the sake of e5planation* we have com#ined the two files into ;(ist.cpp< file. 't the start of the main method* we have created a list o#"ect as0 (ist listC 7ere the default constructor will #e called. !f you understand the concept of factory* then it is not difficult to know that we have asked the !i"t factory to create a !i"t o#"ect and named it as li"t. 'fter creating the o#"ect* nodes have #een added to it. )e have added the elements with data values * 13* =* Q* $=* =Q and 1$. (ater* the "tart&' method of list is called that will position the (urrent3ode and la"t;urrent3ode at the start of the list. Aow there is no need to worry a#out the implementation of the (ist. ?ather* we will use the interface of the (ist. So the "tart method will take us to the start of the li"t and internally* it may #e array or link list or some other implementation. Then there is a while loop that calls the next&' method of the !i"t. !t moves the pointer ahead and returns a #oolean value i.e. true or false. )hen we reach at the end of the list* the next&' method will return false. !n the while loop we have a (out statement that prints the value of the list elements* employing the ,et&' method. The loop will continue till the next&' method returns true. )hen the pointers reach at the end of the list the next&' will return false. 7ere the loop will come to an end.

Ana)," " of L n% L "t


's stated earlier* we will #e going to analy-e each data structure. )e will see whether it is useful or not. )e will see its cost and #enefit with respect to time and memory. (et us analy-e the link list which we have created with the dynamic memory allocation in a chain form. add /or the addition purposes* we simply insert the new node after the current node. So Madd4 is a one2step operation. )e insert a new node after the current node in the chain. /or this* we have to change two or three pointers while changing the values of some pointer varia#les. 7owever* there is no need of traversing too much in the list. !n case of an array* if we have to add an element in the centre of the array* the space for it is created at first. /or this* all the elements that are after the current pointer in the array* should #e shifted one place to the right. Suppose if we have to insert the element in the start of the array* all the elements to the right one spot are shifted. 7owever* for the link list* it is not something relevant. !n link lists* we can create a new node very easily where the current pointer is pointing. )e have to ad"ust two or three pointers. !ts cost* in terms of &P6 time or computing time* is not much as compared to the one with the use of arrays. remo6e ?emove is also a one2step operation. The node #efore and after the node to #e removed is connected to each other. 6pdate the current pointer. Then the node to #e removed is deleted. 's a result* the node to #e removed is deleted. Zery little work is needed in this case. !f you compare it with arrays* for the deletion of an element from the array* space is created. To fill this space* all the right elements Page 3= of 103

Elementary Data Structures are shifted one spot left. !f the array si-e is two thousand or three thousand* we need to run a loop for all these elements to shift them to left. find The worst2case in find is that we may have to search the entire list. !n find* we have to search some particular element say x. !f found* the (urrent3ode pointer is moved at that node. 's there is no order in the list* we have to start search from the #eginning of the list. )e have to check the value of each node and compare it with 5 1value to #e searched3. !f found* it returns true and points the (urrent3ode pointer at that node otherwise return false. Suppose that x is not in the list* in this case* we have to search the list from start to end and return false. This is the worst case scenario. Though time gets wasted* yet we find the answer that x is not in the list. !f we compare this with array* it will #e the same. )e don4t know whether x is in the array or not. So we have to search the complete array. !n case of finding it* we will remem#er that position and will return true. )hat is the average case9 x can #e found at the first position * in the middle or at the end of the list. So on average* we have to search half of the list. %ac2 !n the #ack method* we move the (urrent pointer one position #ack. :oving the (urrent pointer #ack* one re.uires traversing the list from the start until the node whose next pointer points to current node. 8ur link list is singly linked list i.e. we can move in one direction from start towards end. Suppose our (urrent3ode pointer and la"t;urrent3ode are somewhere in the middle of the list. Aow we want to move one node #ack. !f we have the pointer of la"t;urrent3ode, it will #e easy. )e will assign the value of la"t;urrent3ode to (urrent3ode. >ut how can we move the la"t;urrent3ode one step #ack. )e don4t have the pointer of previous node. So the solution for this is to go at the start of the list and traverse the list till the time you reach the node #efore the la"t;urrent3ode is pointing. That will #e the node whose ne5t pointer contains the value la"t;urrent3ode. !f the (urrent3ode and the la"t;urrent3ode are at the end of the list* we have to traverse the whole list. Therefore #ack operation is not a one step operation. )e not only need a loop here #ut also re.uire time.

Dou-),.) n%ed L "t


!f you look at single link list* the chain is seen formed in a way that every node has a field next that point to the ne5t node. This continues till the last node where we set the next to A6(( i.e. the end of the list. There is a -ead3ode pointer that points to the start of the list. )e have seen that moving forward is easy in single link list #ut going #ack is difficult. /or moving #ackward* we have to go at the start of the list and #egin from there. Do you need a list in which one has to move #ack or forward or at the start or in the end very often9 !f so* we have to use dou#le link list. !n dou#ly2link list* a programmer uses two pointers in the node* i.e. one to point to ne5t node and the other to point to the previous node. Aow our node factory will create a node with three parts.

Page 3 of 103

Elementary Data Structures

prev

element

ne5t

/irst part is )rev i.e. the pointer pointing to the previous node* second part is ele+ent* containing the data to #e inserted in the list. The third part is next pointer that points to the ne5t node of the list. The o#"ective of )rev is to store the address of the previous node. (et4s discuss the code of the node of the dou#ly2link list. This node factory will create nodes* each having two pointers. The interface methods are same as used in singly link list. The additional methods are ,et=rev and "et=rev. The method ,et=rev returns the address of the previous node. Thus its return type is 3ode*. The "et=rev method sets the )rev pointer. !f we have to assign some address to )rev pointer* we will call this method. /ollowing is the code of the dou#ly2linked list node. NF this is the dou#ly2linked list class* it uses the ne5t and prev pointers FN class Aode G pu#lic0 int get13 G return o#"ectC LC NN returns the value of the element void set1int o#"ect3 G this2To#"ect J o#"ectC LC NN set the value of the element AodeF getAe5t13 G return ne5tAodeC LC NN get the address of the ne5t node void setAe5t1AodeF ne5tAode3 NN set the address of the ne5t node G this2Tne5tAode J ne5tAodeC LC AodeF getPrev13 G return prevAodeC LC NN get the address of the prev node void setPrev1AodeF prevAode3 NN set the address of the prev node G this2TprevAode J prevAodeC LC private0 int o#"ectC NN it stores the actual value of the element AodeF ne5tAodeC NN this points to the ne5t node AodeF prevAodeC NN this points to the previous node LC

:ost of the methods are same as those in singly linked list. ' new pointer )rev3ode is added and the methods to get and set its value i.e. ,et=rev and "et=rev. Aow we will use this node factory to create nodes. +ou have to #e very cautious while adding or removing a node in a dou#ly linked list. The order in which pointers are reorgani-ed is important. (et4s have a pictorial view of dou#ly2link list. The diagram can help us understand where the )rev3ode and next3ode are pointing.

Page 3B of 103

Elementary Data Structures head si-eJ

current This is a dou#ly link list. The arrows pointing towards right side are representing next3ode while those pointing towards left side are representing )rev3ode. Suppose we are at the last node i.e. the node with value 1. !n case of going #ack* we usually take the help of )rev3ode pointer. So we can go to the previous node i.e. the node with value D and then to the node with value Q and so on. !n this way* we can traverse the list from the end to start. )e can move forward or #ackward in dou#ly2link list very easily. )e have developed this facility for the users to move in the list easily. (et4s discuss other methods of the dou#ly2linked list. Suppose we have created a new node from the factory with value R. )e will re.uest the node factory to create a new o#"ect using new keyword. The newly created node contains three fields i.e. ob2e(t* )rev3ode and next3ode. )e will store R into o#"ect and connect this new node in the chain. (et4s see how the pointers are manipulated to do that. &onsider the a#ove diagram* the current is pointing at the node with value B. The new node will #e inserted #etween the node with value B and the one with value Q. !n the first step* we assign the address of the node with value Q to the next3ode of the new node. newAode2TsetAe5t1 current2TgetAe5t13 3C current

head

si-eJ

newAode

!n the ne5t step* a programmer points the )rev3ode of the ne 3ode to the node with value B. newAode2Tsetprev1 current 3C

Page 3D of 103

Elementary Data Structures current

head

$ $ newAode

si-eJ

!n the third step* we will set the previous node with value Q to point to the ne 3ode. 1current2TgetAe5t1332TsetPrev1newAode3C current

head

$ $ newAode

B 3 R

si-eJ

Aow the )rev3ode of the node with value Q is pointing to the node with value R. !n the fourth step* the next3ode of the node with value B is pointing to the ne 3ode i.e. the node with value R. Point the (urrent to the ne 3ode and add one to the "i1e of the list. current2TsetAe5t1 newAode 3C current J newAodeC si-e,,C

head

$ $ newAode

B = R current 3

si-eJB

Aow the newAode has #een inserted #etween node with value B and node with value Q.

Page 3Q of 103

Elementary Data Structures

C rcu)ar),.) n%ed ) "t"


(et4s talk a#out circularly linked list. The ne5t field in the last node in a singly2linked list is set to A6((. The same is the case in the dou#ly2linked list. :oving along a singly2linked list has to #e done in a watchful manner. Dou#ly2linked lists have two A6(( pointers i.e. )rev in the first node and next in the last node. ' way around this potential ha-ard is to link the last node with the first node in the list to create a (ir(ularly8lin.ed li"t. The next method in the singly2linked list or dou#ly2linked list moves the (urrent pointer to the ne5t node and every time it checks whether the next pointer is A6(( or not. Similarly the ba(. method in the dou#le2linked list has to #e employed carefully if the current is pointing the first node. !n this case* the )rev pointer is pointing to A6((. !f we do not take care of this* the current will #e pointing to A6((. So if we try to access the A6(( pointer* it will result in an error. To avoid this* we can make a circularly linked list. )e have a list with five elements. )e have connected the last node with the first node. !t means that the next of the last node is pointing towards the first node. current head

si-eJ

The same list has #een shown in a circular shape. current B Q hea $ D 1 si-eJ

+ou have noticed that there is no such node whose next field is A6((. )hat is the #enefit of this9 !f you use the next or ba(. methods that move the (urrent pointer* it will never point to A6((. !t may #e the case that you keep on circulating in the list. To avoid this* we get help from the -ead node. !f we move the -ead node in the circularly linked list* it will not #e certain to say where it was pointing in the start. !ts advantages depend on its use. !f we do not have to move too much in the list and have

Page 3R of 103

Elementary Data Structures no pro#lem checking the A6((* there is little need a circularly2linked list. >ut this facility is availa#le to us. !n this e5ample* we made a circular linked list from a singly link list. !n a singly link list we move in one direction. )e point the next pointer of the last node to the first node. )e can do the same with the dou#ly2linked list. The )rev pointer of the first node will point to the last node and the next pointer of the last node will point to the first node. !f you arrange all the nodes in a circle* one of the pointers 1i.e. ne5t pointer3 will move in clockwise direction while the )rev pointers in anti2clockwise direction. )ith the help of these pointers* you can move in the clockwise direction or anti2 clockwise direction. 7ead node pointer will remain at its position. +ou don4t need to change it. !f there is a need to remove the node pointed #y head node than you have to move the head pointer to other node. Aow we don4t have any A6(( pointer in the dou#ly2linked list. )e will not get any e5ception due to A6(( pointers.

/o"e&hu" *ro-)em
Aow we will see an e5ample where circular link list is very useful. This is Sosephus Pro#lem. &onsider there are 10 persons. They would like to choose a leader. The way they decide is that all 10 sit in a circle. They start a count with person 1 and go in clockwise direction and skip 3. Person = reached is eliminated. The count starts with the fifth and the ne5t person to go is the fourth in count. Eventually* a single person remains. +ou might ask why someone has to choose a leader in this way. There are some historical stories attached to it. This pro#lem is also studied in mathematics. (et4s see its pictorial view. AJ10* :J3
3

$ 1 10 R Q B D

)e have ten num#ers representing the ten persons who are in a circle. The value of > shows the count. 's the value of > is three* the count will #e three. 3 represents the num#er of persons. Aow we start counting clockwise. 'fter counting up to three* we have the num#er four. The num#er four is eliminated and put in the eliminated column.

Page =0 of 103

Elementary Data Structures AJ10* :J3


3

Eliminated =

$ 1 10 R Q B D

'fter eliminating the num#er four* we will start our counting from num#er five. &ounting up to three* we have num#er eight which is eliminated and so on. Eliminated AJ10* :J3
3

= Q B D R

$ 1 10

!n the end* only num#er five will remain intact. AJ10* :J3 Eliminated = Q $ D
3

10 R 1 B

Page =1 of 103

Elementary Data Structures !f we have ten persons 1A J 103 in a circle and eliminate after counting up to three 1: J 33. !f we start our count from one* who will #e the leader9 )e have studied this earlier and know that the person who is sitting at the fifth position will #ecome the leader.

Suppose if the value of N is 300 or 400 and the value of M is 5 or 10 !o" "ho "ill #e the leader$ %his is a mathemati&al pro#lem "here "e &an &hange the values of N and M %here is a formula "here the values of N' M are allotted (ou &an &al&ulate "ho should #e&ome the leader )ere "e "ill not solve it mathemati&ally *ather' it "ill #e ta&kled as a &omputer pro#lem If you analy+e the pi&tures sho"n a#ove' it gets &lear that this &an #e solved "ith the &ir&ular link list ,e arrange these num#ers in a &ir&ularlylinked list' point the head pointer at the starting num#er and after &alling the next method for three times' "e "ill rea&h the node "hi&h is to #e removed ,e "ill use the remove method to remove the node %hen the next method is &alled thri&e from there and the node is removed ,e "ill &ontinue this till "e have only one node
)e are not concerned with the A6(( pointers* internal to link list. 7owever* if you want to solve this pro#lem and choose the #est data structure* then circular link list is the #est option. )e can also use the list to solve this. (et4s see the code of the program #y which we can solve this pro#lem. The code is as under0 NFThis program solves the Sosephus Pro#lem FN Uinclude Kiostream.hT Uinclude V&(ist.cppV NNcontains the circularly2linked list definition NN The main method void main1int argc* char FargvHI3 G &(ist listC NN creating an o#"ect of list int i* AJ10* :J3C for1iJ1C i KJ AC i,, 3 list.add1i3C NN initiali-ing the list with values list.start13C NN pointing the pointers at the start of the list

NN counting upto : times and removing the element while1 list.length13 T 1 3 G

Page =$ of 103

Elementary Data Structures for1iJ1C i KJ :C i,, 3 list.ne5t13C cout KK Vremove0 V KK list.get13 KK endlC list.remove13C L cout KK Vleader is0 V KK list.get13 KK endlC L )e have included the ;&(ist.cpp<. !t means that we are using the circularly2linked list. !n the main method* ;!i"t factory is called to create a circular link list as ;!i"t li"t; 'fter this* we assign the values to 3 and >. )e have used for loop to add the nodes in the list. )hen this loop finishes* we have ten nodes in the list having values from 1 to 10. >ut here a programmer may not pay attention to the internal details of the list. )e have created a list and stored ten num#ers in it. Then we moved the pointers of the list at the start of the list using the "tart method. !t means that the pointers are pointing at the position from where we want to start the counting of the list. There is a while loop that will continue e5ecuting until only one node is left in the list. !nside this loop* we have a for loop. !t will e5ecute from 1 to >. !t has only one statement i.e. li"t.next&'. This will move the pointer forward three times 1as the value of : is 33. Aow the current pointer is at the =th node. )e called the re+ove method. >efore removing the node* we display its value on the screen using (out. 'gain we come into the -ile loop* now the length of the list is R. The Mfor loop4 will #e e5ecuted. Aow the li"t.next&' is not starting from the start. !t will start from the position where the (urrent pointer is pointing. The (urrent pointer is pointing at the ne5t node to the node deleted. The count will start again. The li"t.next&' will #e called for three times. The current pointer will point at the Qth node. 'gain the remove method will #e called and the (urrent pointer moved to the ne5t node and so on. The nodes will #e deleted one #y one until the length of the list is greater than one. )hen the length of the list is one* the while loop will #e terminated. Aow only one node is left in the list i.e. the leader. )e will display its value using the ,et method. )e can change the values of > and 3. Similarly* these values can #e read from the file or can use the command line arguments to get values. There are many variations of this pro#lem. 8ne variation is that the value of > keeps on changing. Sometimes* it is 3* sometimes = or and so on. Due to this* it will #ecome difficult to think that who will #ecome leader. :ake a picture in your mind that ten persons are sitting in a circle. Every time the value of > is incremented #y one. Aow try to ascertain which position you should sit to get chosen as a leader. +ou may like to write a program to solve this or use the mathematical formula. NNdisplaying the remaining node

Page =3 of 103

Elementary Data Structures

Lecture No. 00
Summary
13 $3 33 =3 >enefits of using circular list '#stract Data Type Stacks Stack !mplementation using arrays

!n the previous lecture* we demonstrated the use of the circular list for the resolution of the Sosephus pro#lem. 'fter writing a program with the help of this data structure* a leader among ten persons was selected. +ou must have noted many things while trying to solve the pro#lem. These things will help us to understand the usage of data structures in &,,* thus making the programming easy. The code of the program is given #elow. Uinclude V&(ist.cppV void main1int argc* char FargvHI3 G &(ist listC int i* AJ10* :J3C for1iJ1C i KJ AC i,, 3 list.add1i3C list.start13C while1 list.length13 T 1 3 G for1iJ1C i KJ :C i,, 3 list.ne5t13C cout KK Vremove0 V KK list.get13 KK endlC list.remove13C L cout KK Vleader is0 V KK list.get13 KK endlC L !n the program* we include the file of the class ;!i"t and create its o#"ect i.e. li"t. Then we solve the pro#lem #y using the add, "tart, len,t-, next, re+ove and ,et methods of the class ;!i"t. !n the program* we have included already2defined data structure ;!i"t. 'fter defining its different methods* we have an interface of ;li"t. There is no need to #e worry a#out the nature of the list i.e. whether it is linked list* dou#ly linked list or an array. /or us* it is only a list to #e manipulated according to our re.uirement. +ou will see that a programmer may use different methods of the list o#"ect to solve the pro#lem. )e add elements to the list #y a simple call of add method and go to the first element of the list #y "tart method. 7ere* the length method is used in the condition of the -ile loop. Then we remove elements from the list and use the next* ,et and re+ove

Page == of 103

Elementary Data Structures methods during this process. )e get the current element #y using the ,et method* then remove it #y calling the re+ove method and then go to the ne5t element #y the method next. This way* all the elements are removed from the list e5cept one element* called the leader. This one element remains there as we e5ecute the while loop one less than the length of the list. !n singly linked list* the Mnext0 returns false when it reaches to the last node due to the fact that the next field of the last node is set to A6((. >ut in a circularly linked list there is no A6((. !t will #e there only when there is no node in the list. The whole process* which we carried out to solve the Sosephus pro#lem* can also #e carried out with functions in &,,. )hile adopting this way 1of writing functions3* we have to write these functions whenever we write another program that manipulates a list. !n this method* we define a class of the data structure list and its different methods for the purpose of manipulation. This way* this class* o#viously its methods too* can #e used in any program where the manipulation of a list is needed. Thus there is re2usa#ility of the code. !n a class* we encapsulate the data and its methods. This shows that we are no longer interested in the internal process of the class. ?ather* we simply use it wherever needed. The circular linked list* earlier used for the resolution of the Sosephus pro#lem* can also #e employed in other pro#lems. )e have a class ;!i"t of this circular linked list through which any num#er of o#"ects of data type of circular linked list can #e created. Thus we can assume the class ;!i"t as a factory* creating as many o#"ects of list as needed. This class and its o#"ects in any program can #e used to solve the pro#lems with the help of its interface. The interface of this class consists of some methods like add, re+ove, next, ba(., ,et and some other simple ones. )hile carrying out programming* we will see that these classes 1o#"ects3 help us very much to solve different pro#lems.

1enef t" of u" n' c rcu)ar ) "t


)hile solving the Sosephus pro#lem* it was witnessed that the usage of circular linked list helped us make the solution trivial. )e had to "ust write a code of some lines that solved the whole pro#lem. !n the program* we included the class ;!i"t 1which is of our data structure i.e. circular linked list3 and used all of its methods according to the re.uirements. There was no pro#lem regarding the working of the methods. )e "ust called these methods and their definition in the class ;!i"t worked well. Aow we will see what happens if we solve the Sosephus pro#lem #y using an array instead of the class in our program. !n this case* we have to define an array and write code to move #ack and forth in the array and to remove different elements properly in a particular order. ' programmer needs to #e very careful while doing this* to reach the solution of the pro#lem. Thus our code #ecomes very comple5 and difficult for someone to understand and modify it. :oreover we cannot use this code in some other pro#lem. Aote that here we are talking a#out the use of an array in the main program* not in the class that defines the ;!i"t data structure. There is no need to #e worried whether an array* singly linked list* dou#ly linked list is used or circular linked list #eing employed internally in implementing the list in defining the class of list data type. )e only want that it should create o#"ects of list. The usage of the class of a data structure simplifies the code of the program. )e can also use this class

Page = of 103

Elementary Data Structures wherever needed in other programs. This shows that the choice of appropriate data structures can simplify an algorithm. !t can make the algorithm much faster and efficient. !n this course* we will see that there are different data structures* which makes the algorithms very easy to solve our pro#lems. (ater* we will see how some elegant data structures lie at the heart of ma"or algorithms. There is also a course dedicated to study different algorithms and recipes that can #e used to solve host of comple5 pro#lems. :oreover* we will study different data structures in detail and see that with the use of a proper data structure* we can solve a pro#lem efficiently. ' properly constructed data structure will always help in the solution of pro#lems.

A-"tract Data T,&e


' data type is a collection of values and a set of operations on those values. That collection and these operations form a mathematical construct that may #e implemented with the use of a particular hardware or software data structure. The term a#stract data type 1'DT3 refers to the #asic mathematical concept that defines the data type. )e have discussed four different implementations of the list data structure. !n case of implementation of the list with the use of an array* the si-e of the array gives difficulty if increased. To avoid this* we allocate memory dynamically for nodes #efore connecting these nodes with the help of pointers. /or this purpose* we made a singly linked list and connected it with the ne5t pointer to make a chain. :oving forward is easy #ut going #ack is a difficult task. To overcome this pro#lem* we made a dou#ly linked list using )rev and next pointers. )ith the help of these pointers* we can move forward and #ackward very easily. Aow we face another pro#lem that the )rev pointer of first node and the next pointer of the last node are A6((. Therefore* we have to #e careful in case of A6(( pointers. To remove the A6(( pointers* we made the circular link list #y connecting the first and last node. The program employing the list data structure is not concerned with its implementation. )e do not care how the list is #eing implemented whether through an array* singly linked list* dou#ly linked list or circular linked list. !t has #een witnessed that in these four implementations of the list* the interface remained the same i.e. it implements the same methods like add, ,et, next, "tart and re+ove etc. This proves that with this encapsulation attained #y making a class* we are not concerned with its internal implementation. The implementation of these a#stract data types can #e changed anytime. These a#stract data types are implemented using classes in &,,. !f the list is implemented using arrays while not fulfilling the re.uirements* we can change the list implementation. !t can #e implemented with the use of singly2link list or dou#ly link list. 's long as the interface is same* a programmer can change the internal implementation of the list and the program using this list will not #e affected at all. This is the a#stract data type 1'DT3. )hat we care a#out is the methods that are availa#le for use* with the (ist 'DT i.e. add* ,et* and re+ove etc methods. )e have not studied enough e5amples to understand all the #enefits of a#stract data types. )e will follow this theme while developing other 'DT. )e will pu#lish the interface and keep the freedom to change the implementation of 'DT without effecting users of the 'DT. The &,, classes provide a programmer an a#ility to create such 'DTs. )hat #enefits can we get with the help of these 'DTs and classes9 )hen we develop an 'DT or a class or factory then the users of this factory are independent of how this factory works internally. Suppose that we have ordered the car factory 1car class3 to

Page =B of 103

Elementary Data Structures produce a new car and it replies after a long time. !f we ordered the remove method to remove one node and we are waiting and it keeps on working and working. Then we might think that its implementation is not correct. 'lthough* we are not concerned with the internal implementation of this 'DT yet it is necessary to see whether this 'DT is useful for solving our pro#lem or not. !t should not #ecome a #ottleneck for us. !f the method we are using is too much time consuming or it has some pro#lem in terms of algorithm used. 8n one side* we only use the interfaces provided #y these 'DTs* classes* or factories as long as they do what they promise. )e are not concerned with the internal details. 8n the other hand* we have to #e careful that these factories or methods should not take too much time so that these will not #e useful for the pro#lem. This distinction will always #e there. Sometimes* the source code of classes is not provided. )e will #e provided li#raries* as standard li#raries are availa#le with the compiler. These classes are in compiled form i.e. are in o#"ect form or in #inary form. 8n opening these files* you will not see the &,, code* rather #inary code. )hen you read the assem#ly language code* it will give some idea what this #inary code is a#out. +ou can view the interface methods in the .- file. 's an application programmer* you have to see that the 'DTs #eing used are written in a #etter way. The point to #e remem#ered here is that you should not worry a#out the internal implementation of these 'DTs. !f we want to change the internal implementation of the 'DTs* it can #e done without affecting the users of these 'DTs. )hile writing a program* you should check its performance. !f at some point* you feel that it is slow* check the 'DTs used at that point. !f some 'DT is not working properly* you can ask the writer of the 'DT to change the internal implementation of that 'DT to ensure that it works properly.

Stac%"
(et4s talk a#out another important data structure. +ou must have a fair idea of stacks. Some e5amples of stacks in real life are stack of #ooks* stack of plates etc. )e can add new items at the top of the stack or remove them from the top. )e can only access the elements of the stack at the top. /ollowing is the definition of stacks. ;Stack is a collection of elements arranged in a linear order< (et4s see an e5ample to understand this. Suppose we have some video cassettes. )e took one cassette and put it on the ta#le. )e get another cassette and put it on the top of first cassette. Aow there are two cassettes on the ta#le2 one at the top of other. Aow we take the third cassette and stack it on the two. Take the fourth cassette and stack it on the three cassettes. Aow if we want to take the cassette* we can get the fourth cassette which is at the top and remove it from the stack. Aow we can remove the third cassette from the stack and so on. Suppose that we have fifty cassettes stacked on each other and want to access the first cassette that is at the #ottom of the stack. )hat will happen9 'll the cassettes will fell down. !t will not happen e5actly the same in the computer. There may #e some pro#lem. !t does not mean that our data structure is incorrect. 's we see in the a#ove e5ample that the top most cassette will #e removed first and the new cassette will #e stacked at the top. The same e5ample can #e repeated with the #ooks.

Page =D of 103

Elementary Data Structures !n the daily life* we deal with the stacked goods very carefully. Aow we will discuss how to create a stack data structure or a factory* going to create stack o#"ect for us. )hat will #e the attri#utes of this o#"ect9 During the discussion on the list* we came to know that a programmer adds values in the list* removes values from the list and moves forward and #ackward. !n case of a stack too* we want to add things and remove things. )e will not move forward or #ackward in the stack. Aew items can #e added or removed at the top only. )e can not suggest the removal of the middle element of the stack. (et4s talk a#out the interface methods of the stacks. Some important methods are0 7ethod Name push153 pop13 top13 Description !nsert 5 as the top element of the stack ?emove the top element of the stack and return it. ?eturn the top element without removing it from the stack.

The )u"-&x' method will take an element and insert it at the top of the stack. This element will #ecome top element. The )o)&' method will remove the top element of the stock and return it to the calling program. The to)&' method returns the top2most stack element #ut does not remove it from the stack. The interface method names that we choose has special o#"ective. !n case of list* we have used add* re+ove* ,et* "et as the suita#le names. 7owever* for stack* we are using )u"-* )o) and to). )e can depict the activity from the method name like push means that we are placing an element on the top of the stack and pushing the other elements down. The e5ample of a hotel4s kitchen may help understand the concept of stacks in a comprehensive manner. !n the kitchen* the plates are stacked in a cylinder having a spring on the #ottom. )hen a waiter picks a plate* the spring moves up the other plates. This is a stack of plates. +ou will feel that you are pushing the plates in the cylinder and when you take a plate from the cylinder it pops the other plates. The top method is used to get the top2 most element without removing it. )hen you create classes* interfaces and methods* choose such names which depicts what these method are doing. These names should #e suita#le for that class or factory. (et4s discuss the working of stack with the help of a diagram.

Page =Q of 103

Elementary Data Structures

top top top top $ push1$3 $ push1 3 $ push1D3 D

1 D $ push113

top top D $ 1 pop13

$1 D $ push1$13 $1 top D top $ pop13 D $ top pop13 $ pop13

't the start* the stack is empty. /irst of all* we push the value $ in the stack. 's a result* the num#er $ is placed in the stack. )e have a to) pointer that points at the top element. Then we said )u"-&5'. Aow see how $ and are stacked. The num#er is placed at the top of num#er $ and the pointer to) moves one step upward. Then we pushed the num#er D which is placed on the top and the num#er $ and are #elow. Similarly* we push num#er 1. The last figure in the first row shows the stacked values of the num#ers2 1* D* and $. (et4s pop the elements from the stack. The first figure of second row shows the pop operation. 's a result* the num#er 1 is popped. Than again we push the num#er $1 on the stack. The num#er D* * and $ are already in the stack and num#er $1 is pushed at the top. !f we pop now* the num#er $1 is popped. Aow num#er D is at the top. !f we pop again* the num#er D is popped. Pop again and the num#er is popped and num#er $ remains in the stack. 7ere with the help of this diagram* we are proving that the values are added at the top and removed at the top in a stack. The last element to go into the stack is the first to come out. That is why* a stack is known as !9?@ 1(ast !n /irst 8ut3 structure. )e know that the last element pushed in the stack is at the top which is removed when we call pop. (et4s see some other scenarios. )hat happens if we call )o)&' while there is no element9 8ne possi#le way2out is that we have i"A+)ty&' function that returns true if stack is empty and false otherwise. This is a #oolean function that returns false if there is no element in the stack. 8therwise* it will return true. The second option is this that when we call pop on an empty stack* it throws an e5ception. This is a concept of advanced &,,. E5ception is also a way to convey that some unusual condition has arisen or something has gone wrong. Suppose* if we have a division method and try to divide

Page =R of 103

Elementary Data Structures some num#er with -ero. This method will throw Mdivision #y -ero4 e5ception. &urrently we will not throw an e5ception #ut use the i"A+)ty&' method. The user who is employing the stack is responsi#le to call the i"A+)ty&' method #efore calling the )o). &all the )o) method if i"A+)ty&' returns false . 8therwise* there will #e a pro#lem.

Stac% 2m&)ementat on u" n' arra,


(et4s discuss the implementation of the stack. Suppose we implement the stack using the arrays. The stack shown in the a#ove diagram may #e considered as an array. 7ere the array is shown vertically. )e can implement the stack using array. The interface will remain as )u"- and )o) methods. The user of the stack does not need to know that the stack is internally implemented with the help of array. The worst case for insertion and deletion from an array may happen when we insert and delete from the #eginning of the array. )e have to shift elements to the right for insertion and left for removal of an element. )e face the same pro#lem while implementing the list with the use of the array. !f we )u"- and )o) the elements from the start of the array for stack implementation* this pro#lem will arise. !n case of )u"-* we have to shift the stack elements to the right. 7owever* in case of )o), after removing the element* we have to shift the elements of stack that are in the array to the left. !f we push the element at the end of the array* there is no need to shift any element. Similarly as the )o) method removes the last element of the stack which is at the end of the array* no element is shifted. To insert and remove elements at the end of the array we need not to shift its elements. >est case for insert and delete is at the end of the array where there is no need to shift any element. )e should implement )u"-&' and )o)&' #y inserting and deleting at the end of an array.

top

1 D

$ 0 1 top J 3

D $

1 3 =

!n the a#ove diagram* on the left side we have a stack. There are four elements in the stack i.e. 1* D* and $. The element 1 is the e5treme2most that means that it is inserted in the end whereas D* * and $ have #een added #efore. 's this is a (!/8 structure so the element 1 should #e popped first. 8n the right side we have an array with positions 0* 1* $* 3 and so on. )e have inserted the num#ers $* * D and 1. )e have decided that the elements should #e inserted at the end of the array. Therefore the most recent element i.e. 1 is at position 3. The to) is the inde5 representing the position of the most recent element. Aow we will discuss the stack implementation in detail using array. )e have to choose a ma5imum si-e for the array. !t is possi#le that the array may Mfill2 up4 if we push enough elements. Aow more elements cannot #e pushed. Aow what

Page 0 of 103

Elementary Data Structures should the user of the stack do9 !nternally* we have implemented the stack using array which can #e full. To avoid this* we write i"?ull&' method that will return a #oolean value. !f this method returns true* it means that the stack 1array3 is full and no more elements can #e inserted. Therefore #efore calling the )u"-&x'* the user should call i"?ull&' method. !f i"?ull&' returns false* it will depict that stack is not full and an element can #e inserted. This method has #ecome the part of the stack interface. So we have two more methods in our interface i.e. i"A+)ty&' and i"?ull&'. Aow we will discuss the actual &,, code of these operations. These methods are part of stack class or stack factory. )e have an array named # while (urrent is its inde5. The code of )o)&' method is as0 int pop13 G return 'Hcurrent22IC L !n this method* the recent element is returned to the caller* reducing the si-e of the array #y 1. The code of )u"- method is0 void push1int 53 G 'H,,currentI J 5C L )e know that ++(urrent means that add one to the (urrent and then use it. That also shows that element x should #e inserted at (urrent plus one position. 7ere we are not testing that this (urrent inde5 has increased from the array si-e or not. 's discussed earlier that #efore using the )u"- method* the user must call i"?ull&' method. Similarly it is the responsi#ility of the user to call the i"A+)ty&' method #efore calling the )o) method. Therefore there is no if statement in the )u"- and )o) method. The code of the to)&' method is0 int top13 G return 'HcurrentIC L This method returns the element at the current position. )e are not changing the value of (urrent here. )e simply want to return the top element. int isEmpty13 G return 1 current JJ 21 3C L

Page 1 of 103

Elementary Data Structures This method also tests the value of the (urrent whether it is e.ual to 21 or not. !nitially when the stack is created* the value of (urrent will #e 21. !f the user calls the i"A+)ty&' method #efore pushing any element* it will return true. int is/ull13 G return 1 current JJ si-e213C L This method checks that the stack is full or not. The varia#le "i1e shows the si-e of the array. !f the (urrent is e.ual to the "i1e minus one* it means that the stack is full and we cannot insert any element in it. )e have determined the cost and #enefit of all the data structures. Aow we will see how much time these methods take. ' .uick e5amination shows that all the five operations take constant time. !n case of list* the find method takes too much time as it has to traverse the list. )hereas the add and re+ove methods are relatively .uick. The methods of stack are very simple. There is no comple5ity involved. )e insert element at one side and also remove from that side not in the middle or some other place. Therefore we need not to carry out a lot of work. During the usage of the array* the stack methods )u"-* )o)* to)* i"?ull and i"A+)ty all are constant time operations. There is not much difference of time #etween them. The complete code of the program is0 NF Stack implementation using array FN Uinclude Kiostream.hT NF The Stack class FN class Stack G pu#lic0 Stack13 G si-e J 10C current J 21CL NNconstructor int pop13G return 'Hcurrent22ICL NN The pop function void push1int 53G'H,,currentI J 5CL NN The push function int top13G return 'HcurrentICL NN The top function int isEmpty13Greturn 1 current JJ 21 3CL NN )ill return true when stack is empty int is/ull13G return 1 current JJ si-e213CL NN )ill return true when stack is full private0 int o#"ectC int currentC int si-eC int 'H10IC LC NN The main method int main13 Page $ of 103

NN The data element NN !nde5 of the array NN ma5 si-e of the array NN 'rray of 10 elements

Elementary Data Structures G Stack stackC NN creating a stack o#"ect NN pushing the 10 elements to the stack for1int i J 0C i K 1$C i,,3 G if1Wstack.is/ull133 NN checking stack is full or not stack.push1i3C NN push the element at the top else cout KKVYn Stack is full* canEt insert new elementVC L NN pop the elements at the stack for 1int i J 0C i K 1$C i,,3 G if1Wstack.isEmpty133 NN checking stack is empty or not cout KK VYn The popped element J V KK stack.pop13C else cout KKVYn Stack is empty* canEt popVC L L The output of the program is0 Stack is full* canEt insert new element Stack is full* canEt insert new element The popped element J R The popped element J Q The popped element J D The popped element J B The popped element J The popped element J = The popped element J 3 The popped element J $ The popped element J 1 The popped element J 0 Stack is empty* canEt pop Stack is empty* canEt pop 7owever* a programmer finds the si-e2related pro#lems in case of an array. )hat should we do when the array is full9 )e can avoid the si-e limitation of a stack implemented with an array #y using a linked list to hold the stack elements. /urther discussion on this issue will #e made in the ne5t lecture.

Page 3 of 103

Elementary Data Structures

Lecture No. 03
Summary
Stack /rom the Previous (ecture Stack 6sing (inked (ist Stack !mplementation0 'rray or (inked (ist 6se of Stack Precedence of 8perators E5amples of !nfi5 to Postfi5

Stac% #rom the *rev ou" Lecture


)e started discussing Bta(. data structure and its implementation in the previous lecture. )e also implemented stack structure using an array and wrote code for its )u"-&', )o)&' and to)&' operations. )e reali-ed that we have to specify the si-e of the array #efore using it whether we declare it statically or dynamically. 'rrays are of fi5ed si-e and when they #ecome full* no more elements can #e added to them. !n order to get to know that the array has gone full* we wrote the i"?ull&' method. !t #ecame the responsi#ility of the user of the stack structure to call i"?ull&' method #efore trying to insert an element using the )u"-&' method otherwise the whole program could crash. i"A+)ty&' method is implemented as a "ta(. can #e empty like a li"t or "et structures. !t is important to understand that i"?ull&' method is there in stack implementation #ecause of limitation of array #ut i"A+)ty&' method is part of the stack characteristics or functionality. 's previously in the implementation of list structure* we used linked list while allocating nodes dynamicallyin order to avoid the fi5ed si-ed limitation of array. Aow in this case also* again to overcome the limitation of array* we are going to make use of linked list in place of array to implement the stack data structure. (et4s see* how we can implement a stack structure using linked list and how the implementation code will look like internally.

Stac% U" n' L n%ed L "t


)e can avoid the si-e limitation of a stack implemented with an array* with the help of a linked list to hold the stack elements. 's needed in case of array* we have to decide where to insert elements in the list and where to delete them so that )u"- and )o) will run at the fastest. Primarily* there are two operations of a stackC )u"-&' and )o)&'. ' stack carries lifo Page = of 103

Elementary Data Structures #ehavior i.e. last in* first out. +ou know that while implementing stack with an array and to achieve lifo #ehavior* we used )u"- and )o) elements at the end of the array. !nstead of pushing and popping elements at the #eginning of the array that contains overhead of shifting elements towards right to )u"- an element at the start and shifting elements towards left to )o) an element from the start. To avoid this overhead of shifting left and right* we decided to )u"- and )o) elements at the end of the array. Aow* if we use linked list to implement the stack* where will we )u"- the element inside the list and from where will we )o) the element9 There are few facts to consider* #efore we make any decision0 2 /or a "in,ly8lin.ed li"t* insert at start or end takes constant time using the -ead and (urrent pointers respectively. 's far as insertion is concerned* it is worka#le and e.ually efficient at the start and end. 2 ?emoving an element at the start is constant time #ut removal at the end re.uires traversing the list to the node one #efore the last. So removing from the start is #etter approach rather than from the end. Therefore* it makes sense to place stack elements at the start of the list #ecause insertion and removal take constant time. 's we don4t need to move #ack and forth within the list* therefore* there is no re.uirement of doubly or (ir(ular lin.ed li"t. Bin,ly lin.ed li"t can serve the purpose. 7ence* the decision is to insert the element at the start in the implementation of )u"- operation and remove the element from the start in the )o) implementation.

head top 1 D 1 D $

$ Fig ,0 Stac2 using array 4on left side5 and lin2ed list 4on right side5

There are two parts of a#ove figure.8n the left hand* there is the stack implemented using an array. The elements present inside this stack are 1* 5* 5 and 2. The most recent element of the stack is 1. !t may #e removed if the )o)1' is called at this point of time. 8n the right side* there is the stack implemented using a linked list. This stack has four nodes inside it which are liked in such a fashion that the very first node pointed #y the -ead pointer contains the value 1. This first node with value 1 is pointing to the node with value 5. The node with value 5 is pointing to the node with value 5 while the node with value is pointing to the last node with value $. To make

Page

of 103

Elementary Data Structures a stack data strcuture using a linked list* we have inserted new nodes at the start of the linked list. (et4s see the code #elow to implement )o)&' method of the stack. int pop13 G 1. int 5 J head2Tget13C $. Aode F p J headC 3. head J head2TgetAe5t13C =. delete pC . return 5C L

't line 1* we have declared x as an int and retrieved one element from the node of the stack that is pointed #y the -ead pointer. ?emem#er* the 3ode class and its get13 method that returns the value inside the node. 't line $* ) is declared as a pointer of type 3ode and address inside the -ead pointer is #eing saved inside this ) pointer. 't line 3* the address of the ne5t node is #eing retrieved with the help of the ,et3ext&' method of the 3ode class and #eing assigned to -ead pointer. 'fter this assignment* the -ead pointer has moved forward and started pointing to the ne5t element in the stack. 't line =* the node o#"ect pointed #y the pointer ) is #eing deallocated 1deleted3. 't line * the function is returning the value of the node retrieved in step 1.

head

top

$ Fig )0 A node remo6ed from the stac2 after the pop45 call

(et4s see the code of the )u"-&' method of the stack0 void push1int 53 G 1. Aode F newAode J new Aode13C $. newAode2Tset153C 3. newAode2TsetAe5t1head3C =. head J newAodeC L Page B of 103

Elementary Data Structures

!n line 1* a new node is created* using the ne 3ode&' statement and returned pointer is assigned to a pointer ne 3ode. So ne 3ode starts pointing to the newly created 3ode o#"ect. !n line $* the value 2 is set into the newly created 3ode o#"ect. !n line 3* the ne5t node of the newly created node is set to the node pointed to #y the -ead pointer using "et3ext&-ead'. !n line =* the -ead pointer is made to point to the newly created node.

head top R D D $

ne1Node

Fig !0 A node added to the stac2 after the push4/5 call These are two primary methods of a stack. >y using the )u"-&' method* we can keep on pushing elements and using the )o)&3 methods. Elements can #e removed from the stack till the time* it gets empty. 's discussed earlier* i"A+)ty&' is the stack characteristic #ut i"?ull&' was implemented #ecause of the si-e limitation of the array. )e are no more using array to implement a stack. ?ather* we have used linked list here for stack implementation. Therefore* i"?ull&' might not #e re.uired here. 'n interesting .uestion arises here. &an we add infinite elements to the stack now. )e should remem#er that this program of stack will run on computer that definitely has a limited memory. :emory or #ddre"" ")a(e of a computer is the space 1physical memory and disk space3 that can #e addressed #y the computer which is limited inlcuding the limited physical memory. Disk space is used as the virtual +e+ory & we will not discuss virtual +e+ory in detail here3. ' computer with 3$2#it addressing can address upto 23281 memory locations and similarly a computer with B=2#it addressing can address upto 26%81 addresses. !f this address space #ecomes full* the stack will definitely #e full. 7owever* the stack implementation is not lia#le for this fullness of address space and it is the limitation of a computer address space. Therefore* we don4t need to call i"?ull&' #efore )u"-ing the element. ?ather* i"A+)ty&' is called #efore )o)ing an element from the stack. (et4s see the remaining methods of the stack while using linked list to implement it. int top13 G return head2Tget13C L Page D of 103

Elementary Data Structures int isEmpty13 G return 1 head JJ A6(( 3C L The a#ove2mentioned methods i.e. to)&' and i"A+)ty&' are very simple functions. 8ne statement inside the to)&' is retrieving the top element 1pointed to #y the -ead pointer3 from the stack and returning it #ack #y value. !t is important to note that to)&' is not removing the element from the stack* #ut only retrieving it. The one statement inside i"A+)ty&' is a check to see if the -ead pointer is not pointing to any node and it is 3:!!. !f the -ead pointer is 3:!! that means the stack is empty* the method returns true otherwise it returns fal"e. 'll four operations )u"-&'* )o)&'* to)&' and i"A+)ty&' take constant time. These are very simple methods and don4t contain loops. They are also not &P6 hungry operation. 'lso note that we have not written i"?ull&' while implementing stack with the linked list.

Stac% 2m&)ementat on4 Arra, or L n%ed L "t


Since #oth implementations support stack operations in constant time* we will see what are the possi#le reasons to prefer one implementation to the other. 2 'llocating and de2allocating memory for list nodes does take more time than pre2 allocated array. :emory allocation and de2allocation has cost in terms of time* especially* when your system is huge and handling a volume of re.uests. )hile comparing the stack implementation* using an array versus a linked list* it #ecomes important to consider this point carefully. 2 (ist uses as much memory as re.uired #y the nodes. !n contrast* array re.uires allocation ahead of time. !n the previous #ullet* the point was the time re.uired for allocation and de2allocation of nodes at runtime as compared to one time allocation of an array. !n this #ullet* we are of the view that with this runtime allocation and de2allocation of nodes* we are also getting an advantage that list consumes only as much memory as re.uired #y the nodes of list. !nstead of allocating a whole chunk of memory at one time as in case of array* we only allocate memory that is actually re.uired so that the memory is availa#le for other programs. /or e5ample* in case of implementing stack using array* you allocated array for 1000 elements #ut the stack* on average* are using 0 locations. So* on the average* R 0 locations remain vacant. Therefore* in order to resolve this pro#lem* linked list is handy. 2 (ist pointers 1-ead, next3 re.uire e5tra memory. &onsider the manipulation of array elements. )e can set and get the individual elements with the use of the array inde5C we don4t need to have additional elements or pointers to access them. >ut in case of linked list* within each node of the list* we have one pointer element called next* pointing to the ne5t node of the list. Therefore* for 1000 nodes stack implemented using list* there will #e 1000 e5tra pointer varia#les. ?emem#er that stack is implemented using Msingly2linked4 list. 8therwise* for dou#ly linked list* this overhead is also dou#led as two pointer varia#les are stored within each node in that case. 2 'rray has an upper limit whereas list is limited #y dynamic memory allocation. !n

Page Q of 103

Elementary Data Structures other words* the linked list is only limited #y the address space of the machine. )e have already discussed this point at reasona#le length in this lecture.

U"e of Stac%
E5amples of uses of stack include2 traversing and evaluating prefi5* infix and postfi5 e5pressions. &onsider the e5pression #+$0 we think of applying the o)erator ;,< to the o)erand" ' and >. )e have #een writing this kind of e5pressions right from our primary classes. There are few important things to consider here0 /irstly* + o)erator re.uires two operators or in other words ;,< is a binary o)erator. Secondly* in the e5pression #+$* the one operand # is on left of the operator while the other operand $ is on the right side. This kind of e5pressions where the operator is present #etween two operands called infix e5pressions. )e take the meanings of this e5pression as to add #oth operands # and $. There are two other ways of writing e5pressions0 )e could write +#$* the operator is written #efore the operands # and $. These kinds of e5pressions are called =refix E5pressions. )e can also write it as #$+* the operator is written after the operands # and $. This e5pression is called =o"tfix e5pression. The prefi5es )re and )o"t refer to the position of the operator with respect to the two operands. &onsider another e5pression in infix form0 # + $ * ;. !t consists of three operands #, $, ; and two operator +,* . )e know that multiplication 13 is done #efore addition 1,3* therefore* this e5pression is actually interpreted as0 # + &$ * ;'. The interpretation is #ecause of the precedence of multiplication 1F3 over addition 1,3. The precedence can #e changed in an e5pression #y using the parenthesis. )e will discuss it a #it later. (et4s see* how can we convert the infi5 e5pression # + &$ * ;' into the postfi5 form. /irstly* we will convert the multiplication to postfi5 form as0 # + &$ ; *'. Secondly* we will convert addition to postfi5 as0 # &$ ; *' + and finally it will lead to the resultant postfi5 e5pression i.e. 0 # $ ; * +. (et4s convert the e5pression &# + $' * ; to postfi5. +ou might have noticed that to overcome the precedence of multiplication operator 1F3 we have used parenthesis around # + $ #ecause we want to perform addition operation first #efore multiplication. &# + $' * ; &# $ +' * ; &# $ +' ; * #$+;* infix for+ (onvert addition (onvert +ulti)li(ation )o"tfix for+

These e5pressions may seem to #e difficult to understand and evaluate at first. >ut this is one way of writing and evaluating e5pressions. 's we are normally used to infi5 form* this postfi5 form might #e little confusing. !f a programmer knows the

Page R of 103

Elementary Data Structures algorithm* there is nothing complicated and even one can evaluate the e5pression manually.

*recedence of !&erator"
There are five #inary operators* called addition* "ubtra(tion* +ulti)li(ation* divi"ion and ex)onentiation. )e are aware of some other #inary operators. /or e5ample* all relational operators are #inary ones. There are some unary operators as well. These re.uire only one operand e.g. [ and ,. There are rules or order of e5ecution of operators in :athematics called precedence. /irstly* the ex)onentiation operation is e5ecuted* followed #y multiplicationNdivision and at the end additionNsu#traction is done. The order of precedence is 1highest to lowest30 E5ponentiation :ultiplicationNdivision F* N 'dditionNsu#traction ,* 2 /or operators of same precedence* the left2to2right rule applies0 ',>,& means 1',>3,&. /or e5ponentiation* the right2to2left rule applies0 ' > & means ' 1> &3 )e want to understand these precedence of operators and infi5 and postfi5 forms of e5pressions. ' programmer can solve a pro#lem where the program will #e aware of the precedence rules and convert the e5pression from infi5 to postfi5 #ased on the precedence rules.

Exam&)e" of 2nf x to *o"tf x


(et4s consider few e5amples to ela#orate the infix and )o"tfix forms of e5pressions #ased on their precedence order0 Postfi' !nfi5 ',> 1$ , B0 [ $3 1' , >3F1& [ D 3 ' > F & [ D , EN/ '>, 1$ B0 , $3 [ '>,&D[F ' > &FD [ E /N,

!n the ne5t lecture we will see* how to convert infix to )o"tfix and how to evaluate )o"tfix form #esides the ways to use stack for these operations.

Page B0 of 103

Elementary Data Structures

Lecture No. 05
Summary
13 $3 33 Evaluating postfi5 e5pressions 'n e5ample !nfi5 to postfi5 &onversion

Eva)uat n' &o"tf x ex&re"" on"


!n the previous lecture* we talked a#out Minfi5 and postfi5 e5pression4 and tried to understand how to write the postfi5 notation of mathematical e5pressions. ' programmer can write the operators either after the operands i.e. postfi5 notation or #efore the operands i.e. prefi5 notation. Some of the e5amples are as under0 Infi' ',> 1$ , B0 [ $3 1' , >3F1& [ D 3 ' > F & [ D , EN/ Postfi' '>, 1$ B0 , $3 [ '>,&D[F ' > &FD [ E /N,

The last e5pression seems a #it confusing #ut may prove simple #y following the rules in letter and spirit. !n the postfi5 form* parentheses are not used. &onsider the infi5 e5pressions as M=,3F 4 and M1=,33F 4. The parentheses are not needed in the first #ut are necessary in the second e5pression. The postfi5 forms are0 =,3F 1=,33F =3 F, =3, F

!n case of not using the parenthesis in the infi5 form* you have to see the precedence rule #efore evaluating the e5pression. !n the a#ove e5ample* if we want to add first then we have to use the parenthesis. !n the postfi5 form* we do not need to use parenthesis. The position of operators and operands in the e5pression makes it clear in which order we have to do the multiplication and addition. Aow we will see how the infi5 e5pression can #e evaluated. Suppose we have a postfi5 e5pression. 7ow can we evaluate it9 Each operator in a postfi5 e5pression refers to the previous two operands. 's the operators are #inary 1we are not talking a#out unary operators here3* so two operands are needed for each operator. The nature of these operators is not affected in the postfi5 form i.e. the plus operator 1,3 will apply on two operands. Each time we read an operand* we will push it on the stack.

Page B1 of 103

Elementary Data Structures )e are going to evaluate the postfi5 e5pression with the help of stack. 'fter reaching an operator* we pop the two operands from the top of the stack* apply the operator and push the result #ack on the stack. Aow we will see an e5ample to comprehend the working of stack for the evaluation of the postfi5 form. 7ere is the algorithm in pseudo code form. 'fter reading this code* you will understand the algorithm.

Stack sC NN declare a stack while1 not end of input 3 G NN not end of postfi5 e5pression e J get ne5t element of input if1 e is an operand 3 s.push1 e 3C else G op$ J s.pop13C op1 J s.pop13C value J result of applying operator Me4 to op1 and op$C s.push1 value 3C L L finalresult J s.pop13C

)e have declared a StackMs4. There is a Mwhile loop4 along with Mnot end of input4 condition. 7ere the input is our postfi5 e5pression. +ou can get the e5pression from the key#oard and use the enter key to finish the e5pression. !n the ne5t statement* we get the ne5t element and store it in Me4. This element can #e operator or operand. The operand needs not to #e single digit. !t may #e of two digits or even more like B0 or $3= etc. The complete num#er is stored in the Me4. Then we have an Mif statement4 to check whether Me4 is an operand or not. !f Me4 is an operand than we wrote ".)u"-&e' i.e. we pushed the Me4 onto the stack. !f Me4 is not the operand* it may #e an operator. Therefore we will pop the two elements and apply that operator. )e pop the stack and store the operand in Mo)24. )e pop the stack again and store the element in Mo)14. Then the operator in Me4 is applied to Mo)14 and Mo)24 #efore storing the result in value. !n the end* we push the Mvalue4 on the stack. 'fter e5iting the loop* a programmer may have only one element in the stack. )e pop this element which is the final result. &onsider the e5ample of =,3F$ having a postfi5 form of =3$F,. 7ere =* 3* and $ are operands whereas , and F are operators. )e will push the num#ers =* 3 and $ on the stack #efore getting the operator F. Two operands will #e popped from the stack and F is #eing applied on these. 's stack is a (!/8 structure* so we get $ first and then 3 as a result of pop. So $ is store in Mo)14 and 3 in Mo)24. (et4s have a look on the program again. 8n applying F on these* we will push the result 1i.e. B3 on the stack. The Mwhile loop4 will #e e5ecuted again. !n case of getting the ne5t input as operand* we will push it on the stack otherwise we will pop the two operands and apply the operator on these. 7ere the ne5t element is the operator ,. So two operands will #e popped from the stack i.e. B and =. )e will apply the operator plus on these and push the result 1i.e. 103 on the stack. The input is finished. Aow we will pop the stack to get the final result i.e. 10.

Page B$ of 103

Elementary Data Structures

An Exam&)e
!n the earlier e5ample* we have used the stack to solve the postfi5 e5pression. (et4s see another comprehensive e5ample. The postfi5 e5pression is0 B$3,23Q$N,F$3, )e want to evaluate this long e5pression using stack. (et4s try to solve it on paper. )e have five columns here i.e. input* op1* op$* value and stack. )e will run our pseudo code program. !n the start* we read the input as a result we get num#er B. 's B is operand* so it will #e pushed on the stack. Then we have num#er $ which will also #e pushed on the stack. Aow $ is the most recent element. The ne5t element is the num#er 3 that will also #e pushed on the stack. Aow* there are three elements on the stack i.e. 3* $ and B. The num#er 3 is the most recent. 8n popping* we will get the num#er 3 first of all. The ne5t element is M,4* an operator. Aow the else part of our pseudo code is e5ecuted. )e will pop two operands from the stack and apply the operator 1,3 on these. The num#er 3 will #e stored in varia#le o)2 and num#er $ in o)1. The operator 1,3 will #e applied on these i.e. $,3 and the result is stored in value. Aow we will push the value 1i.e. 3 on the stack. Aow we have two num#ers on the stack i.e. and B. The num#er is the most recent element. The ne5t element is M2M. 's it is also an operator* so we will pop the two elements from the stack i.e. and B. Aow we have in op$ and B in op1. 8n applying the operator 123* we will get the result as 1 1B2 3. )e can4t say op$ 2 op1. The result 113 will #e pushed on stack. Aow on the stack* we have only one element i.e. 1. Ae5t three elements are operands so we pushed 3* Q and $ on the stack. The most recent element is $. The ne5t input is an operator in the e5pression i.e. MN4* we will pop two elements from the stack. The num#er $ will #e stored in o)2 while num#er Q in o)1. )e apply the operator 1N3 on the o)1 and o)2 i.e. 1op1Nop$3* the result is = 1i.e. QN$3. )e push the result on the stack. )e have* now* three elements i.e. =* 3* and 1 on the stack. The ne5t element is operator plus 1,3. )e will pop the two elements i.e. = and 3 and will apply the operator 1,3. The result 1D3 will #e pushed on the stack. The ne5t input element is operator multiply 1F3. )e will pop the two elements i.e. D and 1 and the result 1DF1 J D3 is pushed on the stack. +ou have noted that whenever we have an operator in the input e5pression* we have two or more elements on the stack. 's the operators we are using are #inary and we need two operands for them. !t will never #e the case that you want to pop two elements from the stack and there is only one or no element on the stack. !f this happens than it means there is an error in the program and you have popped more values than re.uired. The ne5t input element is $ that is pushed on the stack. )e have* now* the operator 1 3 in the input. So we will pop the two elements* o)2 will hold $ and o)1 will have the num#er D. The operator 1 3 will #e applied on the operands i.e. 1D $3 and the result 1=R3 is pushed on the stack. )e have* now* the num#er 3 in the element #eing pushed on the stack. The last element is the operator plus 1,3. So we pop the two elements i.e. =R and $ and apply the operator on these. The result 1=R,3 J $3 is pushed on the stack. The input e5pression is finished* resulting in the final result i.e. $. This the ta#ular form of the evaluation of the postfi5 e5pression. Input op, op) 6alue stac2

Page B3 of 103

Elementary Data Structures B $ 3 B $ B 3 $ B $ B B B 3 1 1 1 B 1 3 1 Q 3 1 $ Q 3 1 = 3 1 D 1 D $ D =R 3 =R $

, 2 3 Q

, F $ 3 ,

3 1 1 D D =R

= D D $ $ 3

D D D =R =R $

)ith the help of stack we can easily solve a very #ig postfi5 e5pression. Suppose you want to make a calculator that is a part of some application e.g. some spreadsheet program. This calculator will #e used to evaluate e5pressions. +ou may want to calculate the value of a cell after evaluating different cells. Evaluation of the infi5 form programmatically is difficult #ut it can #e done. )e will see another data structure which #eing used to solve the e5pressions in infi5 form. &urrently* we have to evaluate the values in different cells and put this value in another cell. 7ow can we do that9 )e will make the postfi5 form of the e5pression associated with that cell. Then we can apply the a#ove algorithm to solve the postfi5 e5pression and the final result will #e placed at that cell. This is one of the usages of the stack.

2nf x to &o"tf x Conver" on


)e have seen how to evaluate the postfi5 e5pressions while using the stack. 7ow can we convert the infi5 e5pression into postfi5 form9 &onsider the e5ample of a spreadsheet. )e have to evaluate e5pressions. The users of this spreadsheet will employ the infi5 form of e5pressions. &onsider the infi5 e5pressions M',>F&4 and M1',>3F&4. The postfi5 versions are M'>&F,4 and M'>,&F4 respectively. The order

Page B= of 103

Elementary Data Structures of operands in postfi5 is the same as that in the infi5. !n #oth the infi5 e5pressions* we have the order of operands as '* > and then &. !n the postfi5 e5pressions too* the order is the same i.e. '* >* followed #y &. The order of operands is not changed in postfi5 form. 7owever* the order of operators may #e changed. !n the first e5pression M',>F&4* the postfi5 e5pression is M'>&F,4. !n the postfi5 form multiplication comes #efore the plus operator. !n scanning from left to right* the operand M'4 can #e inserted into postfi5 e5pression. /irst rule of algorithm is that if we find the operand in the infi5 form* put it in the postfi5 form. The rules for operators are different. The M,4 cannot #e inserted in the postfi5 e5pression until its second operand has #een scanned and inserted. \eep the e5pression ',>F& in your mind. )hat is the second operand of the plus9 The first operand is ' and the second operand is the result of >F&. The M,4 has to wait until the MF4 has not #een performed. +ou do the same thing while using the calculator. /irst you will multiply the >F& and then add ' into the result. The M,4 has to #e stored away until its proper position is found. )hen M>4 is seen* it is immediately inserted into the postfi5 e5pression. 's M>4 is the operand* we will send the operand to the postfi5 form. &an the M,4 #e inserted now9 !n case of M',>F&4* we cannot insert M,4 #ecause MF4 has precedence. To perform multiplication* we need the second operand. The first operand of multiplication is M>4 while the second one is M&4. So at first* we will perform the multiplication #efore adding result to M'4. !n case of M1',>3F&4* the closing parenthesis indicates that M,4 must #e performed first. 'fter sending the ' and > to postfi5 perform* we can perform the addition due to the presence of the parenthesis. Then & will #e sent to the postfi5 e5pression. !t will #e followed #y the multiplication of the & and the result of ' , >. The postfi5 form of this e5pression is '>,&F. Sometimes* we have two operators and need to decide which to apply first like in this case M,4 and MF4. !n this case* we have to see which operator has higher precedence. 'ssume that we have a function M)r(d&o)1,o)2'4 where o)1 and o)2 are two operators. The function M)r(d&o)1,o)2'4 will return T?6E if o)1 has precedence over o)2* /'S(E otherwise. Suppose we call this function with the arguments MF4 and M,4 i.e. prcd1F* ,3* it will return true. !t will also return true in case #oth o)1 and o)2 are M,4 e.g. if we have ',>,&* then it does not matter which , we perform first. The call )r(d&+ , *' will return false as the precedence of F is higher than the , operator. The M,4 has to wait until F is performed. Aow we will try to form an algorithm to convert infi5 form into postfi5 form. /or this purpose* a pseudo code will #e written. )e will also write the loops and if conditions. The pseudo code is independent of languages. )e will #e using a stack in this algorithm. 7ere* the infi5 e5pression is in the form of a string. The algorithm is as follows0 Stack sC while1 not end of input 3 G c J ne5t input characterC if1 c is an operand 3 add c to postfi5 stringC else G while1 Ws.empty13 OO prcd1s.top13*c3 3G op J s.pop13C Page B of 103

Elementary Data Structures add op to the postfi5 stringC L s.push1 c 3C L while1 Ws.empty13 3 G op J s.pop13C add op to postfi5 stringC L /irst we will declare a stack M"0. The Mwhile loop4 will continue till the end of input. )e read the input character and store it in the M(4. 7ere the input character does not mean one character* #ut an operand or an operator. Then we have a conditional if statement. !f M(4 is an operand* then we will have to add it to postfi5 string. )henever we get an operand in the infi5 form* it will #e added to the postfi5 form. The order of operands does not change in the conversion. 7owever* in this case* the order of operators may change. !f M(4 is the operator* then we will* at first* check that stack is not empty #esides identifying the precedence of the operators #etween the input operator and the operator that is at the top of the stack. !n case of the precedence of the operator that is on the stack is higher* we will pop it from the stack and send to the postfi5 string. /or e5ample if we have F on the stack and the new input operator is ,. 's the precedence of the , operator is less than the F operator* the operands of the multiplication has already #een sent to the postfi5 e5pression. Aow* we should send the F operator to the postfi5 form. The plus operator 1,3 will wait. )hen the while loop sends all such operators to the postfi5 string* it will push the new operator to the stack that is in M(4. !t has to wait till we get the second operand. Then we will again get the input. 8n the completion of the input* the while loop will #e finished. There may #e a case that input may #e completed even at the time when there are still some elements on the stack. These are operators. To check this* we have another while loop. This loop checks if the stack is not empty* pops the operator and put it in the postfi5 string. (et4s take a look at a comprehensive e5ample to understand it. !n case of the infi5 e5pression* ' , > F &* we have three columns* one each for input sym#ol* the postfi5 e5pression and the stack respectively. Aow let4s e5ecute the pseudo code. /irst of all* we get the M'4 as input. !t is an operand so we put it on the postfi5 string. The ne5t input is the plus operator 1,3 which will #e pushed on the stack. 's it is an operator and we need two operands for it. 8n having a look at the e5pression* you might have figure out that the second operand for the plus operator is >F&. The ne5t input is the operand > #eing sent to the postfi5 e5pression form. The ne5t thing we get is the input element as MF4. )e know that the precedence of F is higher than that of the ,. (et4s see how we can do that according to our pseudo code. The )r(d&".to)&', o)' takes two operands. )e will get the top element of the stack i.e. , will #e used as first argument. The second argument is the input operator i.e. F. So the function call will #e as )r(d&+, *' while the function returns false #ecause the precedence of the plus operator is not higher than the multiplication operator. So far* we have only one operand for multiplication i.e. >. 's multiplication is also a #inary operator* it will also have to wait for the second operand. !t has to wait and the waiting room is stack. So we will push it on the stack. Aow the top element of the stack is F. The ne5t sym#ol is M&4. >eing an operand* & will #e added to the postfi5 e5pression. 't this point* our input e5pression has #een completed. 8ur first Mwhile loop4 e5ecutes till the end of input. 'fter the end of the input* the loop will #e terminated. Aow the control Page BB of 103

Elementary Data Structures goes to the second while loop which says if there is something on the stack* pop it and add it the postfi5 e5pression. !n this case* we have F and , on the stack. The F is at the top of the stack. So when we pop* we get F which is at the top of the stack and it will #e added to the postfi5 e5pression. !n the result of second pop* we get the plus operator 1,3 which is also added to the postfi5 e5pression. The stack is empty now. The while loop will #e terminated and postfi5 e5pression is formed i.e. '>&F,.

Sym%ol ' , > F &

postfi' ' ' '> '> '>& '>&F '>&F,

stac2 , , F , F , ,

!f we have to convert the infi5 e5pression into the postfi5 form* the "o# is easily done with the help of stack. The a#ove algorithm can easily #e written in &,, or & language* specially* if you already have the stack class. Aow you can convert very #ig infi5 e5pressions into postfi5 e5pressions. )hy we have done this9 This can #e understood with the help of the e5ample of spreadsheet programming where the value of cell is the evaluation of some e5pression. The user of the spreadsheets will use the infi5 e5pressions as they are used to it. Sometimes we do need the parenthesis in the infi5 form. )e have to evaluate the lower precedence operator #efore the higher precedence operator. !f we have the e5pression 1',>3 F&* this means that we have to evaluate , #efore the multiplication. The o#"ective of using parenthesis is to esta#lish precedence. !t forces to evaluate the e5pression first of all. )e also have to handle parenthesis while converting the infi5 e5pression into postfi5 one. )hen an open parenthesis M1M is read* it must #e pushed on the stack. This can #e done #y setting )r(d&o),C&C ' to #e /'(SE. )hat is the reason to put the parenthesis on the stack9 !t is due to the fact that as long as the closing parenthesis is not found* the open parenthesis has to wait. !t is not a unary or #inary operator. 'ctually* it is a way to show or write precedence. )e can handle the parenthesis #y adding some e5tra functionality in our )r(d function. )hen we call )r(d&o), C&C'* it will return false for all the operators and #e pushed on the stack. 'lso* )r(d& C&C,o) ' is /'(SE which ensures that an operator after M1M is pushed on the stack. )hen a M34 is read. 'll operators up to the first M1M must #e popped and placed in the postfi5 string. To achieve this our function )r(d& o),0'0 ' should return true for all the operators. >oth the M1M and the434 will not go to the postfi5 e5pression. !n postfi5 e5pression* we do not need parenthesis. The precedence of the operators is esta#lished in such a way that there is no need of the parenthesis. To include the handling of parenthesis* we have to change our algorithm. )e have to change the line s.push1c3 to0 if1 s.empty13 XX sym# WJ M34 3

Page BD of 103

Elementary Data Structures s.push1 c 3C else s.pop13C NN discard the M1M !f the input sym#ol is not M34 and the stack is not empty* we will push the operator on the stack. 8therwise* it is advisa#le to pop the stack and discard the M1M. The following functionality has to #e added in the )r(d function. prcd1 M1M* op 3 prcd1 op* M34 3 prcd1 op* M34 3 prcd1 M34* op 3 J J J J /'(SE /'(SE T?6E error for any operator for any operator other than M34 for any operator other than M1M for any operator.

!n the ne5t lecture we will see in detail an e5ample regarding the use of parenthesis.

Page BQ of 103

Elementary Data Structures

Lecture No. 06
Summary
F F F F &onversion from infi5 to postfi5 &,, Templates !mplementation of Stack /unction &all Stack

Conver" on from nf x to &o"tf x


!n the previous lecture* we discussed the way to convert an infi5 notation into a postfi5 notation. During the process of conversion* we saw that there may #e need of parenthesis in the infi5 especially at the times when we want to give a higher precedence to an operator of lower precedence. /or e5ample* if there is a , operator and F operator in an e5pression and a programmer wants the e5ecution of addition #efore the multiplication. To achieve this o#"ect* it is necessary to put parentheses around the operands of , operator. Suppose* there is the e5pression # + $ * ; in which we want to give the precedence to the , operator over F operator. This e5pression will #e written as &# + $' * ;. Aow we are going to discuss the conversion of infi5 e5pression that includes parentheses to the postfi5 e5pression. )e have defined the return values for opening M1Mand closing M34 parentheses in the precedence function. (et4s try to understand this process with the help of an e5ample of converting the infi5 e5pression &# + $' * ; into a postfi5 e5pression. )e will see how our algorithm* discussed earlier* converts this infi5 e5pression into a postfi5 e5pression. To carry out the process of conversion we have three columns sym#ol* postfi5 and stack. The column sym#ol has the input sym#ols from the e5pression. The postfi5 column has the postfi5 string 1e5pression3 after each step and the stack is used to put the operators on it. The whole process of converting the infi5 notation into a postfi5 is given in the following ta#le. This process of conversion is completed in eight steps. Each of the rows of the ta#le depicts one step.

Step Ao. 1 $

Sym#ol 1 '

Postfi5 ' 1 1

Stack

Page BR of 103

Elementary Data Structures 3 = B D Q , > 3 F & ' '> '>, '>, '>,& '>,&F 1, 1, F F

/irst of all* there is the input sym#ol M1M1i.e. opening parenthesis3. 's this is not an operand* it may #e put on the stack. The ne5t input sym#ol is M'4. >eing an operand it goes to the postfi5 string and the stack remains unchanged. Then there is , operator of #inary type. :oreover* there is one operand in the postfi5 string. )e push this , operator on the stack and it has to wait for its second operand. Aow in the input sym#ol* there is an operand M>4. )e put his operand in the postfi5 string. Then after this* there is the closing parenthesis M34 in the input sym#ol. )e know that the presence of a closing parenthesis in the input means that an e5pression 1within the parentheses3 has #een completed. 'll of its operands and operators are present with in the parentheses. 's studied in the algorithm* we discard a closing parenthesis when it comes in the input. Then the operators from the stack are popped up and put in the postfi5 string. )e also pop the opening parenthesis and discard it as we have no need of opening as well as closing parenthesis in the postfi5 notation of an e5pression. This process is carried out in the th row of the ta#le. The , operator is put in the postfi5 string. )e also discard the opening parenthesis* as it is not needed in the postfi5. Aow the ne5t input sym#ol is F. )e put this operator on the stack. There is one operand for the F operator i.e. '>,. The F operator #eing a #inary operator* has to wait for the second operand. M&4 is the Ae5t input sym#ol that is an operand. )e put it in the postfi5 string. 'fter this* the input string 1e5pression3 ends so we come out of the loop. )e check if there is any thing on the stack now9 There is F operator in the stack. )e pop the operator and put it into the postfi5 string. This way* we get the postfi5 form of the given infi5 e5pression that #ecomes #$+;*. !n this postfi5 e5pression* the , operator is #efore the F operator. So addition operation is done #efore the multiplication. This is mainly due to the fact that in the infi5 e5pression* we have put parentheses to give , operator the precedence higher than the F operator. Aote that there are no parentheses in the postfi5 form of the given infi5 e5pression. Aow we apply the evaluation algorithm on this postfi5 e5pression 1i.e. '>,&F3. The two operands ' and >* will go to the stack. Then operator , will pop these operands from the stack* will add them and push the result #ack on the stack. This result #ecomes an operand. Ae5t M&4 will go to the stack and after this F operator will pop these two operands 1result of addition and &3. Their multiplication will lead to the final result. The postfi5 notation is simple to evaluate as compared to the infi5 one. !n postfi5* we need not to worry a#out what operation will #e carried first. The operators in this notation are in the order of evaluation. 7owever* in the infi5 notation* we have to force the precedence according to our re.uirement #y putting parentheses in the e5pression. )ith the help of a stack data structure* we can do the conversion and evaluation of e5pressions easily.

C(( Tem&)ate"
)e can use &,, templates for stack and other data structures. )e have seen that stack

Page D0 of 103

Elementary Data Structures is used to store the operands while evaluating an e5pression. These operands may #e integers* floating points and even varia#les. )e push and pop the operands to and from the stack. !n the conversion of an e5pression* a programmer uses the stack for storing the operators like ,* F* 2* and N etc which are single characters. !n #oth cases* the functionality is the same. )e push and pop things on and from the stack. 't times* we check if the stack is empty or not. Thus identical methods are employed while using stack in evaluating and converting the e5pressions. 7owever* there may #e a difference in the type of the elements 1data3 used in these cases. )e may define a stack* which can store different types of data #ut for the time #eing we are restricting ourselves to the stack that can store elements of only one type. !n &,, programming* we will have to create two classes ?loatBta(. and ;-arBta(. for operands and operators respectively. These classes of stack have the same implementation. Thus* we write the same code twice only with the difference of data type. !s there any method to write the code for the stack once and then use it for different types of data9 This means is there any way that we can make a stack for storing integers* floating points* characters or even o#"ects with the same code written once. The language &,, provides us the facility of writing templates. ' template can #e understood with the e5ample of a factory that #akes #iscuits. The factory may use flour* corn or starch as ingredients of the product. >ut the process of #aking #iscuits is the same whatever ingredients it uses. There is no difference in the machinery for producing #iscuits with different ingredients. So we call the factory as the template for the #iscuits. Similarly in &,, language* a template is a function or class that is written with a generic data type. )hen a programmer uses this function or class* the generic data type is replaced with the data type* needed to #e used in the template function or in the template class. )e only give the data type of our choice while calling a template function or creating an o#"ect of the template class. The compiler automatically creates a version of that function or class with that specified data type. Thus if we write a template class for stack* then later on we can use it for creating a stack for integers* floating points or characters etc. So instead of writing code for different stacks of different data types* we write one code as a template and reuse it for creating different stacks. )e declare the template class in a separate file in addition to the main program file. This file can #e used in our program #y including it in that file. /ollowing is the code of the template class for stack. This is written in the file Stac20h. template Kclass TT class Stack G pu#lic0 Stack13C int empty1void3C NN 1Jtrue* 0Jfalse int push1T O3C NN 1Jsuccessful*0Jstack overflow T pop1void3C T peek1void3C ]Stack13C private0 int topC TF nodesC LC !n the a#ove code the line

Page D1 of 103

Elementary Data Structures template Kclass TT shows that we are going to write a template. 7ere 7 is a varia#le name for generic data type. )e can use any other name #ut generally 7 is used 1T evolves from template3. ' data type will replace this T whenever template is used in a program. Then we declare mem#er functions of the class. To #egin with* there is a constructor of the class with the same name as that of the class i.e. Stack. !t is followed #y the e+)ty &' function and then function )u"- that is declared as follows int push1T O3 C )e have #een using the data 1element3 type int or some other data type in the )u"-&' function. Aow there is 7 written as the data type in the )u"-&' function. This means that the function takes an argument of type 7* here 7 is a generic data type and we will use a proper data type while calling this function in our program. This data type will replace 7. There are also )o) and )ee. functions that take no arguments #ut return the value which is of type 7. The )ee. function is similar to the to) function that returns 1shows3 the element from the top #ut does not remove it from the stack. !n the private section of the class* there are two varia#les. The varia#le to) is used to point to the top of the stack. The pointer node" is used to point to nodes of type 7. )e allocate dynamic memory using this node" pointer. !n the definition of this whole class* 7 is a su#stitution parameter. )hile using the stack class in the program* we will replace this 7 with a proper data type.

2m&)ementat on
Aow we will see how to implement this stack class in our program. /ollowing is the code of the program. )e save this code in the file named Stac20cpp. Uinclude Kiostream.hT Uinclude Kstdli#.hT Uinclude VStack.hV Udefine :'PST'&\S!^E 0 template Kclass TT StackKTT00Stack13 G top J 21C nodes J new TH:'PST'&\S!^EIC L template Kclass TT StackKTT00]Stack13 G delete nodesC L template Kclass TT int StackKTT00empty1void3 Page D$ of 103

Elementary Data Structures G if1 top K 0 3 return 1C return 0C L template Kclass TT int StackKTT00push1TO 53 G if1 top K :'PST'&\S!^E 3 G nodesH,,topI J 5C return 1C L cout KK Vstack overflow in push.YnVC return 0C L template Kclass TT T StackKTT00pop1void3 G T 5C if1 Wempty13 3 G 5 J nodesHtop22IC return 5C L cout KK Vstack underflow in pop.YnVC return 5C L !n this code* we include different files in which one is Stack.h * written earlier to declare the template class Bta(.. )e have defined a constant si-e of the stack to 0 #y writing the line Udefine :'PST'&\S!^E 0 Ae5t is the definition of the constructor. 7ere #efore the signature of the constructor function* we have written template Kclass TT StackKTT 00 Stack13 C This means that we are writing a template function that uses 7 wherever a data type is written. 's we have declared the Stack class as a template class* KTT will #e written with the class name #efore the access specifier 1i.e. 003 while defining a method of the class. Then there is the implementation of the constructor in which we assign the value [1 to to) and allocate memory #y using the ne operator for stack of si-e :'PST'&\S!^E of type 7 and put its starting address in the pointer node". !t is pertinent to note that we create an array of type 7 1i.e. a generic type3. Similarly we define the destructor ]Stack* which frees the memory #y deleting the nodes. Then there are the different methods of the stack i.e. e+)ty&'* )u"-&'* and )o)&'. Page D3 of 103

Elementary Data Structures )e define all the methods in the same way as done in case of the constructor. !t means that while writing te+)late D(la"" 7< at the start* we use 7 wherever a data type can #e used. The function e+)ty&' returns a >oolean parameter. !t returns 1 that means T?6E if the stack is empty i.e. if top is less than 0. 8therwise it returns -ero i.e. /'(SE if the stack is not empty. )e define the )u"- function as under int StackKTT00push1TO 53 G if1 top K :'PST'&\S!^E 3 G nodesH,,topI J 5C return 1C L cout KK Vstack overflow in push.YnVC return 0C L This function takes an argument x #y reference. !t checks whether there is space in the stack #y checking the value of the to). !f to) is less than the :'PST'&\S!^E* it means there is space availa#le in the stack. Then it puts the element x on the stack and returns 1* indicating that push operation has succeeded. 8therwise* it displays a message of stack overflow and returns -ero which indicates that the element was not put on the stack. Ae5t comes the )o) method. 7ere we see that the value returned #y this method is of type 7. !n the #ody of the function* we define a local varia#le of type 7 and check if the stack is empty. !f it is not empty* we pop the value from the top in varia#le 5 and return it. Aow let4s see the use of this template stack. 7ere we write the +ain program in a separate file including the stack.cpp 1we have written #efore shortly3 to use the stack. /ollowing is the program written in the file main0cpp. This program demonstrates the implementation of the stack. Uinclude VStack.cppV int main1int argc* char FargvHI3 G StackKintT intstackC StackKcharT charstackC int 5J10* yJ$0C char cJE&E* dJEDEC intstack.push153C intstack.push1y3C cout KK Vintstack0 V KK intstack.pop13 KK V* V KK intstack.pop13 KK VYnVC charstack.push1c3C charstack.push1d3C cout KK Vcharstack0 V KK charstack.pop13 KK V* V KK charstack.pop13 KK VYnVC L !n the a#ove code* consider the line Stack KintT intstack C Page D= of 103

Elementary Data Structures This line means that while creating an o#"ect int"ta(. of Stack* the generic data type 7 should #e replaced #y the type int* !n other words* it will #e a stack for integers. The compiler will replace 7 with int wherever it e5ists in the code* providing a version of code with data type int. The compiler does this automatically. Similarly the ne5t line Stack KcharT charstack C creates an o#"ect of Stack that has name (-ar"ta(. and replaces the type 7 with (-ar. !t shows that it will #e a stack of characters. 7ere 7 is replaced with (-ar and a version of code is provided #y the compiler* used for the (-ar data type. Thus we create two o#"ects of two types 1i.e. int and char3 of Stack #y using the same code of the template class. To demonstrate the implementation of Stack* we declare two varia#les of type int and two of type (-ar. Then we push and pop these varia#les on and from the proper stack. )e push the int values on the int"ta(. 1which we have created for int data type3. The values of type other than int on the stack int"ta(. can not #e pushed as we have created it to store the int data type. 'nd then we poop these values from the stack and show on the screen. Similarly we push the (-ar values on the (-ar"ta(. 1a stack to store (-ar values3 #efore displaying these values on the screen with the help of the )o) method to get these values from the stack. Aow we have the three files of our code i.e. "ta(..-, "ta(..()) and +ain.()). 7aving these files in the same directory* we compile the main file 1main.cpp3 and e5ecute it. /ollowing is the output of the a#ove program. intstack0 10* $0 charstack0 &* D !n the a#ove e5ample* we create two o#"ects of Stack to use for two different data types. The compiler automatically provides us two versions of the template code* one for int and the other for (-ar using the same code* written as template. So it is only due to the use of the template utility* provided #y the &,, language only. Ao other language including & provides this utility of templates. !f we write this program in &* the code of the functions of Stack has to #e written repeatedly for each data type. Similarly* we will have to write different versions for using different data types. >ut in templates* a programmer writes the code once and the compiler automatically produces the version of the code with the needed data type. )e have implemented the stack #y using array. !t can also #e implemented with the linked list. The use of array or linked list does not matter here. The implementation of the stack remains the same. The templates are so important that &,, provides a li#rary in which a large num#er of common use functions are provided as templates. This li#rary is a part of the official standard of &,,. !t is called ST( i.e. Standard Template (i#rary. 's a li#rary* it is a tested code #ase. )e can use these templates and implement different concepts for our own data types. ST( is an important code* pre2developed for us. !t is availa#le as a li#rary. Different data structures like stack* .ueue etc is also there in ST(. )e can write programs #y using them. >ut here in this course* our goal is to know what the data structures are* what is functioning and how can they #e written9 So we are writing and discussing the stack templates. +ou can use data structures from ST( in the programming courses or in the professional life. +ou need not to write the stack or Page D of 103

Elementary Data Structures .ueue from the scratch you can simply use them in your programs from ST(.

#unct on Ca)) Stac%


(et4s talk a#out another e5ample of the stack. )e know the functionality of the function calls. )henever a programmer calls a function* he or she passes some arguments or parameters to the function. The function does work on these arguments and returns a value to the calling function or program. This value is known as the return value of the function. )e declare some varia#les inside the function which are local varia#les of the function. These varia#les are demolished when the e5ecution of the function ends. !f there are varia#les in the function that need to #e preserved* we have to take care of them. /or this purpose* we use glo#al varia#les or return a pointer to that varia#le. Aow let4s see how a stack is used in function calls. )e are using dev&,, compiler that actually uses %&& 1glue compiler3* a pu#lic domain compiler. )henever we call a function* the compiler makes a stack that it uses to fulfill this function call. The compiler puts the entries on the stack in the way that first of all i.e. on the top 1i.e. first entry in the stack3 is the return address of the function where the control will go #ack after e5ecuting the function. 'fter it* the ne5t entries on the stack are the arguments of the function. The compiler pushes the last argument of the call list on the stack. Thus the last argument of the call list goes to the #ottom of the stack after the return address. This is followed #y the second last argument of the call list to #e pushed on the stack. !n this way* the first argument of the call list #ecomes the first element on the stack. This is shown in the following figure.

last argument ___ ___ second argument first argument top 222222T return address

!n the calling function* after the e5ecution of the function called* the program continues its e5ecution form the ne5t line after the function call. The control comes #ack here #ecause when the e5ecution of the function ends the compiler pops the address from the stack which it has pushed when the function call was made. Thus the control goes at that point in the program and the e5ecution continues in the calling function or program. &onsider the following code of a function that takes two integer arguments a, b and returns the average of these num#ers. int i`avg 1int a* int #3 G return 1a , #3 N $C L

Page DB of 103

Elementary Data Structures To understand the use of stack* look at the assem#ly language code of the a#ove function that is written as under. glo#l `i`avg `i`avg0 movl =1aesp3* aea5 addl Q1aesp3* aea5 sarl b1* aea5 ret

U 'dd the args U Divide #y $ U ?eturn value is in aea5

The first statement is ,loblEiEav, which shows that it4s a glo#al function that can #e called #y other functions or programs. 'fter it* there is a la#el* written as EiEav,F The ne5t statement is +ovl %&Ge")', Geax. 7ere in this statement* there is the use of stack. 7ere e") is a register in assem#ly language that is now a stack pointer for us 1i.e. top3. The +ovl 1move long3 takes offset = from top 1= is num#er of #ytes* we use = #ytes as in &,, an integer is of = #ytes.3 that means after = #ytes from the top in the stack it gets the value and put it in the eax register. )e know that the compiler pushes the arguments of the function in reverse order on the stack. 'nd pushes return address at the end. Thus the order of stack will #e that on the top will #e the return address and immediately after it will #e the first argument. 7ere in the assem#ly code generated #y the compiler* the compiler pops first argument from offset = and puts it in eax register. The ne5t statement is addl Q1aesp3* aea5 The addl takes offset Q from the stack pointer that is second argument and adds it to eax. Thus in the previous two statements* the compiler got the first argument i.e. a from the stack and the second argument b from the stack* added them #efore putting the result in eax. The ne5t statement sarl b1* aea5 is the division statement of assem#ly language. This statement divides the value in eax #y $ and thus eax has the resultant value. The last statement i.e. ret* returns the value on the top of the stack to the caller function. So we have seen the use of stack in the e5ecution of a function and how the arguments are passed to the function* how the functions return its return value and finally how the control goes #ack to the caller function .'ll this process is e5ecuted #y using a stack. 'll the things a#out the functionality of the function calls are necessary to understand as these will #e needed while going to write our own compilers. The whole process we have discussed a#out the use of stack in function calling is known as run time environment. Different data structures are also used in run time environment of the computer. )e know that an e5ecuta#le program while in run* is loaded in the memory and #ecomes a process. This process is given a #lock of memory which it uses during its e5ecution. Even the operating system* in which we are working* itself takes memory. Suppose we are running many programs simultaneously* which for e5ample include #rowser* :S )ord* E5cel and dev2&,,. )e can also run programs written #y us. Every program which we run takes a #lock of memory and #ecomes a process. The following figure Page DD of 103

Elementary Data Structures shows a part of memory in which different programs occupy a #lock of memory for their e5ecution.

Process 1 1#rowser3 )e can also see the details of specific time. !f we press the there appears a window ta". is the figure of the task many columns i.e. P!D :emory usage* page faults* !N8 >ytes. Process 3 1)ord3 Process = 1E5cel3 Process $ 1Dev2&,,3 )indows 8s all the programs running at a key com#ination ;trl8#lt8Hel* +ana,er on the screen. /ollowing manager. !n the figure* there are 1process !D3* &P6* &P6 time* ?eads* !N8 )rites* !N8 ?ead

Page DQ of 103

Elementary Data Structures

7ere the thing of our interest is the first* second and fifth column. These columns are !mage Aame* P!D and :em 6sage 1i.e. memory usage3. Aow look at the row where ex)lorer.exe is written in the first column. The process !D 1P!D3 of it is QQQ and memory usage is =BRB\. This means that the process si-e of e5plorer.e5e in the memory is =BRB \ilo >ytes 1\>3. 'll the processes in the first column of the task manager are present in the memory of the computer at that time. The column !mage name has the names of the processes #eing e5ecuted. These have e5tension .exe #ut there may #e other e5ecuta#le programs that have e5tension other than .exe. The following figure shows the internal memory organi-ation of a process.

Process 1 1#rowser3 Process 3 1)ord3 Process = 1E5cel3 Process $ 1Dev2&,,3

&ode Static data Stack Page DR of 103

Elementary Data Structures

This shows that the first part of the memory of the process is for the code. This is the code generated #y the compiler of &,,* S'Z' or Z> etc with respect to the language in which the actual code was written. Then the static data of the program occupies the memory. This holds the glo#al varia#les and different varia#les of o#"ects. Then in the memory of the process* there is stack. 'fter it there is heap. The stack and heap are used in function calls. )e have discussed the use of stack in function calls. )hen we allocate memory dynamically in our programs* it is allocated from the heap. The use of heap is a topic related to some programming course or to the operating system course.

Lecture No. 07
Summary
:emory 8rgani-ation Stack (ayout During a /unction &all @ueues @ueue 8perations !mplementing @ueue @ueue using 'rray 6se of @ueues

Memor, !r'an 8at on


>y the end of last lecture* we discussed the uses of stack to develop a process from an e5ecuta#le file and then in function calls. )hen you run an e5ecuta#le* the operating system makes a process inside memory and constructs the followings for that purpose. 2 ' code section that contains the #inary version of the actual code of the program written in some language like &N&,, 2 ' section for static data including glo#al varia#les 2 ' stack and

Page Q0 of 103

Elementary Data Structures


2 2

/inally* a heap

Stack is used in function calling while heap area is utili-ed at the time of memory allocation in dynamic manner.

Process 1 1>rowser3 Process 3 1)ord3 Process = 1E5cel3 Process $ 1Dev2&,,3 )indows 8S

&ode Static Data Stack

7eap

?i, 1. >e+ory @r,ani1ation

Stac% La,out dur n' a #unct on Ca))


Parameters 1/3 (ocal varia#les 1/3 ?eturn address 1/3 Parameters 1%3 sp At point of call sp Parameters 1/3 (ocal varia#les 1/3 ?eturn address 1/3 sp Parameters 1%3 (ocal varia#les 1%3 ?eturn address 1%3 After Call Parameters 1/3 (ocal varia#les 1/3 ?eturn address 1/3

During Execution of G /ig $0 Stack (ayoutC )hen function / calls function %

Page Q1 of 103

Elementary Data Structures The a#ove diagrams depict the layout of the stack when a function ? calls a function I. 7ere sp stands for stack pointer. 't the very left* you will find the layout of the stack "ust #efore function ? calls function I. The parameters passed to function ? are firstly inserted inside the stack. These are followed #y the local varia#les of the function ? and finally the memory address to return #ack after the function ? finishes. Sust #efore function is made to the function I* the parameters #eing passed to the function I, are inserted into the stack. !n the ne5t diagram* there is layout of the stack on the right side after the call to the function I. &learly* the local varia#les of the function % are inserted into the stack after its parameters and the return address. !f there are no local varia#les for a function* the return address is inserted 1pushed3 on to the stack. The layout of the stack* when the function I finishes e5ecution is shown on the right. +ou can see that the local varia#les of function % are no more in the stack. They have #een removed permanently along with the parameters passed to the function %. Aow* it is clear that when a function call is made* all local varia#les of the called function and the parameters passed to it* are pushed on to the stack and are destroyed* soon after the the completion of the called function4s e5ecution. !n &N&,, language* the varia#les declared as "tati( are not pushed on the stack. ?ather* these are stored in another separate section allocated for "tati( data of a program. This section for ,lobal or "tati( data can #e seen in the fig 1 of this lecture. !t is not destroyed till the end of the process4s e5ecution. !f a varia#le* say x is declared as "tati( inside function I* x will #e stored in the "tati( data section in the process4s memory. )hereas* its value is preserved across I function calls. The visi#ility of x is restricted to the function I only. >ut a "tati( varia#le declared as a (la"" data is availa#le to all +e+ber fun(tion" of the (la"" and a "tati( varia#le declared at ,lobal scope 1outside of any class or function #ody3 is availa#le to all functions of the program. Aow* let4s move on to another data structure called Jueue.

9ueue"
' .ueue is a linear data structure into which items can only #e inserted at one end and removed from the other. !n contrast to the stack* which is a (!/8 1(ast !n /irst 8ut3 structure* a .ueue is a /!/8 1/irst !n /irst 8ut3 structure. The usage of .ueue in daily life is pretty common. /or e5ample* we .ueue up while depositing a utility #ill or purchasing a ticket. The o#"ective of that .ueue is to serve persons in their arrival orderC the first coming person is served first. The person* who comes first* stands at the start followed #y the person coming after him and so on. 't the serving side* the person who has "oined the .ueue first is served first. !f the re.uirement is to serve the people in some sort of priority order* there is a separate data structure that supports priorities. The normal .ueue data structure* presently under discussion* only supports /!/8 #ehavior. Aow* let4s see what are the operations supported #y the .ueue.

9ueue !&erat on"


The .ueue data structure supports the following operations0 Operation Description

Page Q$ of 103

Elementary Data Structures en.ueue1P3 de.ueue13 front13 isEmpty13 Place P at the rear of the .ueue. ?emove the front element and return it. ?eturn front element without removing it. ?eturn T?6E if .ueue is empty* /'(SE otherwise

2m&)ement n' 9ueue


There are certain points related to the implementation of the .ueue. Suppose we are implementing .ueue with the help of the linked 2list structure. /ollowing are the key points associated with the linked list implementations0 2 !nsert works in constant time for either end of a linked list. 2 ?emove works in constant time only. 2 Seems #est that head of the linked list #e the front of the .ueue so that all removes will #e from the front. 2 !nserts will #e at the end of the list. front rear front rear

Fig !0 :ueue implementation using lin2ed list The a#ove figure shows Jueue elements on the left with two pointers front and rear. This is an a#stract view of the .ueue* independent of its implementation method of array or linked list. 8n the right side is the same Jueue *using linked list and pointers of front and rear. )hen deJueue&' function is called once* the front element 1 is removed. The picture of the Jueue showing one element removal is also depicted #elow. Aote that front pointer has #een moved to the ne5t element 5 in the list afer removing the front element 1. #fter deJueue&' i" (alled on(e front rear 1 front D rear $

Fig #0 8emo6al of one element from 9ueue using de9ueue45 Aow at this stage of the Jueue* we will call en.ueue 1R3 to insert an element / in it. . The following figure shows that the new element is inserted at the rear end and rear pointer starts pointing this new node with element /. 't this point of time* the code of these functions of deJueue&' and enJueue&' should not #e an issue.

Page Q3 of 103

Elementary Data Structures

Kueue after enJueue&/' (all front front rear D $ R D $ R rear

Fig "0 Insertion of one element using en9ueue4/5 Aote that in this Jueue data structure* the new elements are inserted at rear end and removed from the front. This is in contrast to "ta(. structure where the elements are inserted and removed from the same end. (et4s see the code for .ueue operations0 NF ?emove element from the front FN 1. int de.ueue13 $. G 3. int 5 J front2Tget13C =. AodeF p J frontC . front J front2TgetAe5t13C B. delete pC D. return 5C Q. L NF !nsert an element in the rear FN R. void en.ueue1int 53 10. G 11. AodeF newAode J new Aode13C 1$. newAode2Tset153C 13. newAode2TsetAe5t1A6((3C 1=. rear2TsetAe5t1newAode3C 1 . rear J newAodeC 1B. L !n de.ueue13 operation* at line 3* the front element is retrieved from the .ueue and assigned to the int varia#le x. !n line =* the front pointer is saved in 3ode pointer varia#le ). !n line * the front pointer is moved forward #y retrieving the address of the ne5t node #y using front8<,et3ext&' and assigning it to the front pointer. !n line B* the node pointed to #y the front pointer is deleted #y using delete front statement. 't the end of deJueue&' implementation* the value of deleted node that was saved in the int varia#le x, is returned #ack. The enJueue&int ' is used to add an element in the Jueue. !t inserts the element in the rear of the Jueue. 't line 11* a new 3ode o#"ect is created using the ne 3ode&' statement and the returned starting address of the created o#"ect is assigned to the ne 3ode pointer varia#le. Page Q= of 103

Elementary Data Structures !n line 1$* the value of the passed in parameter x, is set in the newly created node o#"ect using the "et&' method. !n line 13* the next pointer in the newly created node is set to 3:!!. !n line 1=* the newly created node is set as the ne5t node of the node currently pointed #y the rear pointer. !ne line 1 * the rear pointer is set to point to the newly created node. The code of two smaller functions is as under0 NF To retrieve the front element FN int front13 G return front2Tget13C L NF To check if the .ueue is empty FN int isEmpty13 G return 1 front JJ A6(( 3C L The front&' method is used to retrieve the front element. This is the oldest element inserted in the .ueue. !t uses the ,et&' method of the 3ode class. The i"A+)ty&' method is used to check whether the .ueue is empty or not. !t checks the address inside the front pointer* if it is 3:!!. 9t ill return true indicating that the .ueue is empty or vice versa. )hile studying stack data structure* we implemented it #y using #oth array and linked list. /or .ueue* until now we have #een discussing a#out implementing .ueue using linked list. Aow* let4s discuss implementing .ueue with the help of an array.

9ueue u" n' Arra,


' programmer keeps few important considerations into view account #efore implementing a .ueue with the help of an array0 !f we use an array to hold the .ueue elements* #oth insertions and removal at the front 1start3 of the array are e5pensive. This is due to the fact that we may have to shift up to ;n< elements. /or the stack* we needed only one end #ut for a .ueue* #oth are re.uired. To get around this* we will not shift upon removal of an element.

Page Q of 103

Elementary Data Structures

front

real 1 0 D 1 $ $ 3 = B D

front . Fig $0 :ueue implemented using an array

rear !

!n the a#ove figure* .ueue implementation using array is shown. 's the array si-e is 4* therefore* the inde5 of the array will #e from 0 to 5. The num#er of elements inside array are 1* 5* 5 and 2, placed at start of the array. The front and rear in this implementation are not pointers #ut "ust inde5es of arrays. front contains the starting inde5 i.e. 0 while rear comprises 3. (et4s see* how the enJueue&' works0 en.ueue1B3 front real 1 0 D 1 . $ front $ 3 B = rear # B D

/ig D. !nsertion of one element B 's shown in the a#ove diagram* an element i.e. 6 has #een inserted in the Jueue. Aow* the rear inde5 is containing % while the front has the same 0 inde5. (et4s see the figure of the array when another element 4 is inserted in the .ueue. en.ueue1Q3 real 1 0 D 1 $ front . /ig Q. !nsertion of another element Q )hen an element is removed from the .ueue. !t is removed from the front inde5. de.ueue1 3 front real D 0 1 $ $ 3 B = Q Page QB of 103 B D $ 3 B = " Q B rear D

front

1 D

$ B Q

$ B Q

Elementary Data Structures

'fter another call of deJueue&' function0 de.ueue1 3 front real $ 0 1 $ front ) /ig 10. ?emoval of another element from front )ith the removal of element from the .ueue* we are not shifting the array elements. The shifting of elements might #e an e5pensive e5ercise to perform and the cost is increased with the increase in num#er of elements in the array. Therefore* we will leave them as it is. en.ueue1R3 en.ueue11$3 front real $ 0 1 $ front ) 3 B = + Q R B rear 1$ D 3 B = " Q B rear D

$ B Q

$ B Q R 1$

/ig 11. !nsertion of elements in the .ueue 'fter insertion of two elements in the .ueue* the array that was used to implement it* has reached its limit as the last location of the array is in use now. )e know that there is some pro#lem with the array after it attained the si-e limit. )e o#served the similar pro#lem while implementing a stack with the help of an array. )e can also see that two locations at the start of the array are vacant. Therefore* we should can consider how to use those locations appropriately in to insert more Page QD of 103

Elementary Data Structures elements in the array. 'lthough* we have insert and removal operations running in constantly* yet we created a new pro#lem that we cannot insert new elements even though there are two places availa#le at the start of the array. The solution to this pro#lem lies in allowing the .ueue to ra) around. 7ow can we ra) around9 )e can use circular array to implement the .ueue. )e know how to make a linked list circular using pointers. Aow we will see how can we make a circular array. 0 front $ B Q R rear 1$ B /ig 1$. &ircular array to implement .ueue R Q B = $ 3 rear + D 1 front 1$ $ )

The num#er of locations in the a#ove circular array are also eight* starting from inde5 0 to inde5 5. The inde5 num#ers are written outside the circle incremented in the clock2wise direction. To insert an element 21 in the array * we insert this element in the location* which is ne5t to inde5 5. en.ueue1$13 front rear D 0 $1 1$ R Q B = $ 1 front $ ) si *

$ B Q R 1$ $1 B /ig 13. 'n element added in circular array 3 rear . no;lements +

Aow* we will have to maintain four varia#les. front has the same inde5 2 -ile t-e* "i1e is 4. C rear0 has moved to inde5 0 and noAle+ent" is 5. Aow* we can see that rear inde5 has decreased instread of increasing. !t has moved from inde5 5 to 0. front is containing inde5 2 i.e. higher than the inde5 in rear. (et4 see* how do we implement the enJueue&' method. void en.ueue1 int 53 G 1. rear J 1rear , 13 a si-eC $. arrayHrearI J 5C 3. noElements J noElements , 1C L !n line 1 of the code* 1 is added in rear and the mod operator 1that results in Page QQ of 103

Elementary Data Structures remainder of the two operands3 is applied with "i1e varia#le. This e5pression on the right of assignment in line 1 can result from 0 to 5 as si-e is containing value 4. This operator ensures that value of this e5pression will always #e from 0 to 5 and increase or decrease from this. This resultant is assigned to the rear varia#le. !n line $* the x 1the value passed to enJueue&' method to insert in the .ueue3 is inserted in the array at the rear inde5 position. Therefore* in the a#ove case* the new element 21 is inserted at inde5 0 in the array. !n line 3* noAle+ent" is added to accumulate another element in the .ueue. (et4s add another element in the .ueue. en.ueue1D3 front rear D 0 $1 1$ R Q B = /ig 1=. 'nother element added in circular array Aow* the .ueue* rather the array has #ecome full. !t is important to understand* that .ueue does not have such characteristic to #ecome full. 8nly its implementation array has #ecome full. To resolve this pro#lem* we can use linked list to implement a .ueue. /or the moment* while working with array* we will write the method i"?ull&'* to determine the fullness of the array. int is/ull13 G return noElements JJ si-eC L int isEmpty13 G return noElements JJ 0C L i"?ull&' returns true if the num#er of elements 1noAle+ent"3 in the array is e.ual to the "i1e of the array. 8therwise* it returns false. !t is the responsi#ility of the caller of the .ueue structure to call i"?ull&' function to confirm that there is some space left in the .ueue to enJueue&' more elements. Similarly i"A+)ty&' looks at the num#er of elements 1noAle+ent"3 in the .ueue. !f there is no element* it returns true or vice versa.. (et4s see the deJueue&' method. $ 1 D front $ ) si *

$ B Q R 1$ $1 D B 3 rear , no;lements *

Page QR of 103

Elementary Data Structures 0 rear D $1 1$ R Q B = /ig 1 . Element removed from the circular array 1 D front $ # si *

de.ueue13 front

B Q R 1$ $1 D B 3 rear , no;lements *

int de.ueue13 G int 5 J arrayHfrontIC front J 1front , 13 a si-eC noElements J noElements 2 1C return 5C L !n the first line* we take out an element from the array at front inde5 position and store it in a varia#le x. !n the second line* front is incremented #y 1 #ut as the array is circular* the inde5 is looped from 0 to 5. That is why the +od &G' is #eing used. !n the third line* num#er of elements 1noAle+ent"3 is reduced #y 1 and finally the saved array element is returned.

U"e of 9ueue"
)e saw the uses of stack structure in infix* )refix and )o"tfix e5pressions. (et4s see the usage of .ueue now. 8ut of the numerous uses of the .ueues* one of the most useful is "i+ulation. ' simulation program attempts to model a real2world phenomenon. :any popular video games are simulations* e.g.* Sim&ity* /light Simulator etc. Each o#"ect and action in the simulation has a counterpart in the real world. &omputer simulation is very powerful tool and it is used in different high tech industries* especially in engineering pro"ects. /or e5ample* it is used in aero plane manufacturing. 'ctually &omputer Simulation is full2fledged su#"ect of &omputer Science and contains very comple5 :athematics* sometimes. /or e5ample* simulation of computer networks* traffic networks etc. !f the simulation is accurate* the result of the program should mirror the results of the real2world event. Thus it is possi#le to understand what occurs in the real2world without actually o#serving its occurrence. (et us look at an e5ample. Suppose there is a #ank with four tellers. ' customer enters the #ank at a specific time 1t13 desiring to conduct a transaction. 'ny one of the four tellers can attend to the customer. The transaction 1withdraws* deposit3 will take a certain period of time 1t23. !f a teller is free* the teller can process the customer4s transaction immediately and the customer leaves the #ank at t1+t2. !t is possi#le that none of the four tellers is free in which case there is a line of customers at each teller. 'n arriving customer proceeds to the #ack of the shortest line and waits for his turn. The customer leaves the #ank at t2 time units after reaching the front of Page R0 of 103

Elementary Data Structures the line. The time spent at the #ank is t2 plus time waiting in line. So what we want to simulate is the working environment of the #ank that there are specific num#er of .ueues of customers in the #ank in front of the tellers. The tellers are serving customers one #y one. ' customer has to wait for a certain period of time #efore he gets served and #y using simulation tool* we want to know the average waiting time of a #ank customer. )e will talk a#out this simulation in the ne5t lecture and will do coding also in order to understand it well.

Page R1 of 103

Elementary Data Structures

Lecture No. 10
Summary
13 $3 33 =3 @ueues Simulation :odels Priority @ueue &ode of the >ank simulation

9ueue"
!n the previous lecture* we discussed the .ueue data structure and demonstrated its implementation #y using array and link list. )e also witnessed the usefulness of .ueue as data structure in the simulation e5ample. This concept can #e further ela#orated with a daily life e5ample relating to #anking sector. Suppose* customers want to deposit or withdraw money from a #ank* having four cashiers or tellers. The teller helps you in depositing the money or withdrawing the money from the same window. This window is known as teller window. The customer needs some service from the #ank like depositing the money* #ill etc. This transaction needs some time that may #e few minutes. ' person enters the #ank and goes to the teller who is free and re.uests him to do the "o#. 'fter the completion of the transaction* the person goes out of the #ank. Aow we will discuss a scenario when there is a lot of rush of customers. The tellers are "ust four. Aow the tellers are #usy and the new customers will form a .ueue. !n this e5ample* we need a .ueue in front of each of the tellers. ' new customer enters the #ank and analy-es the four .ueues and wants to "oin the shortest .ueue. This person has to wait for the persons in front of him to #e served. 'nother person may come #ehind him. !n this simulation* we will restrict the person from changing the .ueue. ' person comes into the #ank at 10 8 clock. 7is transaction time is minutes. 7e has to wait for another fifteen minutes in the .ueue. 'fter this* the teller serves him in min. This person comes at 10 am and waits for fifteen minutes. 's the transaction time is minutes* so he will leave the #ank at 10$0. Aow this is the situation of simulation and we have to write a program for this. )e can go to some #ank and analy-e this situation and calculate the time. 't the end of the day* we can calculate the average time for each of the customer. This time can #e 30 minutes. 7ere we will simulate this situation with the help of a computer program. This is the real life e5ample. (et4s see the picture of simulations to understand what is happening in the #ank. !n the picture #elow* we have four tellers and four .ueues* one for each of the tellers. Each teller is serving a customer. )hen the transaction of a customer is completed* he will leave the #ank.

Page R$ of 103

Elementary Data Structures

te))er 1

te))er 2

te))er $

te))er +

' person enters the #ank. 7e sees that all the four tellers are #usy and in each .ueue there are two persons waiting for their turn. This person chooses the .ueue no. 3. 'nother person enters the #ank. 7e analy-ed all the .ueues. The .ueue no 3 is the #iggest and all other are having $ persons in the .ueue. 7e chooses the .ueue no 1.

te))er 1

te))er 2

te))er $

te))er +

Aow we have three persons waiting in .ueue no 1 and 3 and two persons waiting in .ueue no $ and =. The person in .ueue no.1 completes his transaction and leaves the #ank. So the person in the front of the .ueue no. 1 goes to the teller and starts his transaction. Similarly the person at .ueue Ao. 3 finishes his transaction and leaves the premises. The person in front of .ueue num#er 3 goes to the teller. 'nother person enters the #ank and goes to the .ueue Ao. 1. This activity goes on. The .ueues #ecome #igger and shorter. The persons coming in the #ank have to wait.

Page R3 of 103

Elementary Data Structures !f the .ueues are shorter* people have to wait for less time. 7owever* if the .ueues are longer* people have to wait for more time. The transactions can also take much more time* keeping the people waiting. Suppose four persons come with #ig amount and their transaction takes too much time. These are all parameters which we can incorporate in our simulation making it real. /or this* we have carry out more programming. )ith the introduction of these parameters in the simulation* it will #e more close to the real life situation. Simulation* #eing a very powerful techni.ue* can yield the results* very close to some real life phenomenon.

S mu)at on Mode)"
(et4s discuss little #it a#out the simulation models. Two common models of simulation are time2#ased simulation and event2#ased simulation. !n time2#ased simulation* we maintain a timeline or a clock. The clock ticks and things happen when the time reaches the moment of an event. Suppose we have a clock in the computer. The minute hand moves after every minute. )e know the time of the customer4s entry into the #ank and are aware that his transaction takes minutes. The clock is ticking and after minutes* we will ask the customer to leave the #ank. !n the program* we will represent the person with some o#"ect. 's the clock continues ticking* we will treat all the customers in this way. Aote that when the customer goes to some teller* he will take minutes for his transaction. During this time* the clock keeps on ticking. The program will do nothing during this time period. 'lthough some other customer can enter the #ank. !n this model* the clock will #e ticking during the transaction time and no other activity will take place during this time. !f the program is in some loop* it will do nothing in that loop until the completion of the transaction time. Aow consider the #ank e5ample. 'll tellers are free. &ustomer &1 comes in $ minutes after the opening of the #ank. Suppose that #ank opens at R000 am and the customer arrives at R00$ am. 7is transaction 1withdraw money3 will re.uire = minutes. &ustomer &$ arrives = minutes after the #ank opens 1R00= am3. 7e needs B minutes for transaction. &ustomer &3 arrives 1$ minutes after the #ank opens and needs 10 minutes for his transaction. )e have a time line and marks for every min.
%ime 2minutes3 0 1 1 3 4 5 0 / . 10 11 11 13 14 15

C1 n C2 n

C1 out C2 out C$ n

&1 comes at $ min* &$ enters at = min. 's &1 needs = min for his transaction* so he leaves at B min. &$ re.uires B min for the processing so &$ leaves at 10 min. Then &3

Page R= of 103

Elementary Data Structures enters at 1$ min and so on. This way* the activity goes on. Therefore* we can write a routine of the clock. )e take a varia#le (lo(. representing the clock. The clock will run for $= hrs. >anks are not open for $= hrs #ut we will run our loop for $= hrs. The pseudo code is as under0 clock J 0C while 1 clock KJ $=FB0 3 G NN one day read new customerC if customer.arrivaltime JJ clock insert into shortest .ueueC check the customer at head of all four .ueues. if transaction is over remove from .ueue. clock J clock , 1C L The varia#le (lo(. is initiali-ed to -ero. The while loop runs for $= hrs. Then we read a new customer. This information may #e coming from some file. The if statement is checking the arrival time of the customer. 7e comes 10 minutes after the opening of the #ank. So when this time is e.ual to the clock* we insert the customer in the shortest .ueue. Then we will check the transaction time of all the four customers at each teller. !f the transaction time of any customer ends* we will remove it from the .ueue and he will leave the #ank. !n the end* we increment the clock with one minute. 's seen in the a#ove statements* some activity takes place when the clock reaches at the event time 1that is the time to enter the #ank or leave the #ank arrives3. !f the customer4s arrival time has not come* the first if statement #ecomes false and we do nothing. Similarly if the transaction of customer is not finished* the second if statement #ecomes false. Then this while loop will simply add one min to the clock. This is the clock2 #ased 1time2 #ased3 simulation. (et4s discuss the other type of simulation i.e. the event2#ased simulation. Don4t wait for the clock to tick until the ne5t event. &ompute the time of ne5t event and maintain a list of events in increasing order of time. ?emove an event from the list in a loop and process it. (et4s see the time line again.

Page R of 103

Elementary Data Structures

%ime 2minutes3 0 1 1 3 4 5 0 / . 10 11 11 13 14 15

C1 n C2 n

C1 out C2 out C$ n

Event 10 $ mins &1 in Event $0 = mins &$ in Event 30 B mins &1 out Event =0 10 mins &$ out Event 0 1$ mins &3 in

The customer &1 comes at $ min and leaves at B min. &ustomer &$ comes at = min and leaves at 10 min and so on. )e have written the events list in the a#ove figure. Do not see the clock #ut see the events on time. Event 1 occurs at $ min that is the customer &1 enters the #ank $ minutes after its opening. Event $ is that &$ enters at = min. Event 3 is that the customer &1 leaves the #ank at B min. Event = is that the &$ leaves the #ank at 10 min and event is that &3 enters the #ank at 1$ min. 7ere we have a list of events. 7ow can we process them9 )e will make a .ueue of these events. ?emove the event with the earliest time from the .ueue and process it. !nsert the newly created events in the .ueue. ' .ueue where the de2.ueue operation depends not on /!/8* is called a priority .ueue.

*r or t, 9ueue
's stated earlier* the .ueue is a /!/8 1/irst in first out3 structure. !n daily life* you have also seen that it is not true that a person* who comes first* leaves first from the .ueue. (et4s take the e5ample of traffic. Traffic is stopped at the signal. The vehicles are in a .ueue. )hen the signal turns green* vehicles starts moving. The vehicles which are at the front of the .ueue will cross the crossing first. Suppose an am#ulance comes from #ehind. 7ere am#ulance should #e given priority. !t will #ypass the .ueue and cross the intersection. Sometimes* we have .ueues that are not /!/8 i.e. the person who comes first may not leave first. )e can develop such .ueues in which the condition for leaving the .ueue is not to enter first. There may #e some priority. 7ere we will also see the events of future like the customer is coming at what time and leaving at what time. )e will arrange all these events and insert them in a priority .ueue. )e will develop the .ueue in such a way that we will get the event which is going to happen first of all in the future. This data structure is known as priority .ueue. !n a sense* /!/8 is a special case of priority .ueue in which priority is given to the time of arrival. That means the person who comes first has the higher priority while the one who comes later* has the low priority. +ou will see the priority .ueue #eing used at many places especially in the operating systems. !n operating systems* we have .ueue of different processes. !f some process comes with higher priority* it will #e processed first. 7ere we have seen a variation of .ueue. )e will use the priority .ueue in the simulation. The events will #e inserted in the .ueue and the event going to occur first in future* will #e popped.

Page RB of 103

Elementary Data Structures

)hat are the re.uirements to develop this simulation9 )e need the &,, code for the simulation. There will #e a need of the .ueue data structure and o#viously* the priority .ueue. !nformation a#out the arrival of the customers will #e placed in an input file. Each line of the file contains the items 1arrival time* transaction duration3. 7ere are a few lines from the input file. 00 30 10 K2 customer 1 00 3 0 K2 customer $ 00 =0 0Q 00 = 0$ 00 0 0 00 1$ 01 00 13 01 01 0R The first line shows the customer 1. ;00 30 10< means &ustomer 1 arrives 30 minutes after the opening of the #ank. 7e will need 10 minutes for his transaction. The last entry ;01 01 0R< means customer arrives one hour and one minute after the #ank opened and his transaction will take R minutes and so on. The file contains similar information a#out the other customers. )e will collect the events now. The first event to occur is the arrival of the first customer. This event is placed in the priority .ueue. !nitially* the four teller .ueues are empty. The simulation proceeds as follows0 when an arrival event is removed from the priority .ueue* a node representing the customer is placed on the shortest teller .ueue. 7ere we are trying to develop an algorithm while maintaining the events .ueue. 'fter the opening of the #ank* the arrival of the first customer is the first event. )hen he enters the #ank all the four tellers are free. Suppose he goes to the first teller and starts his transaction. 'fter the conclusion of his transaction* he leaves the #ank. )ith respect to events* we have only two events* one is at what time he enters the #ank and other is at what time he leaves the #ank. )hen other customers arrive* we have to maintain their events. !f the customer is the only one on a teller .ueue* an event for his departure is placed on the priority .ueue. 't the same time* the ne5t input line is read and an arrival event is placed in the priority .ueue. )hen a departure event is removed from the event priority .ueue* the customer node is removed from the teller .ueue. 7ere we are dealing with the events* not with the clock. )hen we come to know that a person is coming at say R0$0am* we make an event o#"ect and place it in the priority .ueue. Similarly if we know the time of leaving of the customer from the #ank* we will make an event and insert it into the priority .ueue. )hen the ne5t customer in the .ueue is served #y the teller* a departure event is placed on the event priority .ueue. )hen the other customer arrives* we make an event o#"ect and insert it into the priority .ueue. Aow the events are generated and inserted when the customer arrives. >ut the de2 .ueue is not in the same fashion. )hen we de2.ueue* we will get the event which is going to occur first.

Page RD of 103

Elementary Data Structures )hen a customer leaves the #ank* the total time is computed. The total time spent #y the customer is the time spent in the .ueue waiting and the time taken for the transaction. This time is added to the total time spent #y all customers. 't the end of the simulation* this total time divided #y the total customers served will #e average time consumed #y customers. Suppose that 300 customers were served* then we will divide the total time #y 300 to get the average time. So with the help of simulation techni.ue* we will get the result that x customers came today and spent y time in the #ank and the average time spent #y a customer is 1.

Code of the 1an% S mu)at on


(et4s have a look on the &, code of this simulation. Uinclude KiostreamT Uinclude KstringT Uinclude Kstrstream.hT Uinclude V&ustomer.cppV Uinclude V@ueue.hV Uinclude VPriority@ueue.cppV Uinclude VEvent.cppV @ueue .H=IC NN teller .ueues Priority@ueue p.C NNevent(istC int totalTimeC int count J 0C int customerAo J 0C main 1int argc* char FargvHI3 G &ustomerF cC EventF ne5tEventC NN open customer arrival file ifstream data1Vcustomer.datV* ios00in3C NN initiali-e with the first arriving customer. ?eadAew&ustomer1data3C )hile1 p..length13 T 0 3 G ne5tEvent J p..remove13C c J ne5tEvent2Tget&ustomer13C if1 c2TgetStatus13 JJ 21 3G NN arrival event int arrTime J ne5tEvent2TgetEventTime13C int duration J c2TgetTransactionDuration13C int customerAo J c2Tget&ustomerAum#er13C process'rrival1data* customerAo* arrTime* duration * ne5tEvent3C

Page RQ of 103

Elementary Data Structures L else G NN departure event int .inde5 J c2TgetStatus13C int departTime J ne5tEvent2TgetEventTime13C processDeparture1.inde5* departTime* ne5tEvent3C L L )e have included lot of files in the program. 8ther than the standard li#raries* we have ;u"to+er.())* Kueue.-* =riorityKueue.()) and Avent.()). )ith the help of these four files* we will create ;u"to+er o#"ect* Kueue o#"ect* =riorityKueue o#"ect and Avent o#"ect. +ou may think that these are four factories* creating o#"ects for us. 's there are four tellers* so we will create e.ual num#er of .ueues 1Kueue J[%] 3. Then we create a priority .ueue o#"ect )J from the =riorityKueue factory. )e declare total7i+e* (ount and (u"to+er3o as int. These are glo#al varia#les. !n the main method* we declare some local varia#les of customer and event. 'fterwards* the customer.dat file for the input data is opened as0 ifstream data1Vcustomer.datV* ios00in3C )e read the first customers data from this file as0 readAew&ustomer1data3C 7ere data is the input file stream associated to (u"to+er.dat. )e will read the arrival time and time of transaction from the file of the first customer. 'fter reading it* we will process this information. Aow there is the -ile loo) i.e. the main driver loop. !t will run the simulation. /irst thing to note is that it is not clock2#ased which is that the loop will e5ecute for $= hours. 7ere we have the condition of priority .ueue4s length. The varia#le )J represents the event .ueue. !f there are some events to #e processed* the .ueue )J will not #e empty. !ts length will not #e -ero. )e get the ne5t event from the priority .ueue* not from the .ueue. The method )J.re+ove&' 1de2.ueue method3 will give us the event which is going to happen first in future. The priority of events is according the time. !n the event o#"ect we have the (u"to+er3o. !n the if statement* we check the status of the customer. !f the status is [1* it will reflect that this is the new customer arrival event. )e know that when a new customer enters the #ank* he will look at the four tellers and go to the teller where the .ueue is smallest. Therefore in the program* we will check which is the smallest .ueue and insert the customer in that .ueue. !f the event is a#out the new customer* the if statement returns true. )e will get its arrival time* duration and customer num#er and assign it to the varia#les arr7i+e, duration and (u"to+er3o respectively. )e will call the method )ro(e""#rrival&' and pass it the a#ove information.

Page RR of 103

Elementary Data Structures !f the status of the customer is not e.ual to [1* it means that the customer is in one of the four .ueues. The control will go to else part. )e will get the status of the customer which can #e 0* 1* $ and 3. 'ssign this value to Jindex. (ater on* we will see how these values are assigned to the status. )e will get the departure time of the customer and call the )ro(e""He)arture&' method. !n the main driver loop* we will get the ne5t event from the event .ueue. !n this case* events can #e of two types i.e. arrival event and the departure event. )hen the person enters the #ank* it is the arrival event. !f any .ueue is empty* he will go to the teller. 8therwise* he will wait in the .ueue. 'fter the completion of the transaction* the customer will leave the #ank. !t is the departure event. (et4s discuss the function read3e ;u"to+er&'. This function is used to read the data from the file. void readAew&ustomer1ifstreamO data3 G int hour*min*durationC if 1data TT hour TT min TT duration3 G customerAo,,C &ustomerF c J new &ustomer1customerAo* hourFB0,min* duration3C c2TsetStatus1 21 3C NN new arrival EventF e J new Event1c* hourFB0,min 3C p..insert1 e 3C NN insert the arrival event L else G data.close13C NN close customer file L L 7ere* we have used the TT to read the -our* +inute and duration from the file. Then we create a customer o#"ect ( from the customer factory with the ne keyword. )e pass the (u"to+er3o* arrival ti+e and transaction duration to the constructor of the customer o#"ect. 'fter the o#"ect creation* it is time to set its status to [1. This means that it is an arriving customer. Then we create an event o#"ect e passing it the customer ( and the arrival ti+e. )e insert this event into the priority .ueue )J. !f there is no more data to read* we go into the else part and close the data file. (et4s see the function )ro(e""#rrival&'. )e have decided that when the customer arrives and no teller is availa#le* he will go to the shortest .ueue. int process'rrival1ifstream Odata* int customerAo* int arrTime* int duration* EventF event3 G int i* small* " J 0C NN find smallest teller .ueue small J .H0I.length13C for1iJ1C i K =C i,, 3 Page 100 of 103

Elementary Data Structures if1 .HiI.length13 K small 3G small J .HiI.length13C " J iC L NN put arriving customer in smallest .ueue &ustomerF c J new &ustomer1customerAo* arrTime* duration 3C c2TsetStatus1"3C NN remem#er which .ueue the customer goes in .H"I.en.ueue1c3C NN check if this is the only customer in the. NN .ueue. !f so* the customer must #e marked for NN departure #y placing him on the event .ueue. if1 .H"I.length13 JJ 1 3 G c2TsetDepartureTime1 arrTime,duration3C EventF e J new Event1c* arrTime,duration 3C p..insert1e3C L NN get another customer from the input readAew&ustomer1data3C L /irst of all* we will search for the smallest .ueue. /or this purpose* there is a for loop in the method. )e will check the length of all the four .ueues and get the smallest one. )e store the inde5 of the smallest .ueue in the varia#le 2. Then we create a customer o#"ect. )e set its status to 2* which is the .ueue no. Then we insert the customer in the smallest .ueue of the four. The customer may #e alone in the .ueue. !n this case* he does not need to wait and goes directly to the teller. This is the real life scenario. )hen we go to #ank* we also do the same. !n the #anks* there are .ueues and everyone has to enter in the .ueue. !f the .ueue is empty* the customers go straight to the teller. 7ere we are trying to simulate the real life scenario. Therefore if the length of the .ueue is one* it will mean that the customer is alone in the .ueue and he can go to the teller. )e calculate his departure time #y adding the arrival time and transaction time. 't this time* the person can leave the #ank. )e create a departure event and insert it into the priority .ueue. !n the end* we read a new customer. This is the wayC a programmer handles the new customers. )henever a new person enters the #ank* we create an event and insert it into the smallest .ueue. !f he is alone in the .ueue* we create a departure event and insert it into the priority .ueue. !n the main while loop* when we remove the event* in case of first future event* it will #e processed. 'fter the completion of the transaction* the person leaves the #ank. )e may encounter another case. There may #e a case that #efore leaving the #ank* more persons arrive and they have to wait in the .ueue for their turn. )e handle this scenario in the departure routine. The code is0

int processDeparture1 int .inde5* int departTime* EventF event3 G Page 101 of 103

Elementary Data Structures &ustomerF cin. J .H.inde5I.de.ueue13C int waitTime J departTime 2 cin.2Tget'rrivalTime13C totalTime J totalTime , waitTimeC count J count , 1C NN if there are any more customers on the .ueue* mark the NN ne5t customer at the head of the .ueue for departure NN and place him on the event(ist. if1 .H.inde5I.length13 T 0 3 G cin. J .H.inde5I.front13C int etime J departTime , cin.2TgetTransactionDuration13C EventF e J new Event1 cin.* etime3C p..insert1 e 3C L L !n this method* we get the information a#out the Jindex* de)art7i+e and event from the main method. )e get the customer #y using the Jindex. Then we calculate the wait time of the customer. The wait time is the difference of departure time and the arrival time. The total time holds the time of all the customers. )e added the wait time to the total time. )e incremented the varia#le (ount #y one. 'fter the departure of this customer* ne5t customer is ready for his transaction. The if statement is doing this. )e check the length of the .ueue* in case of presence of any customer in the .ueue* we will check the customer with the front&' method. )e set its departure time 1eti+e3 #y adding the depart time of the previous customer and his transaction time. Then we create an event and insert it in the priority .ueue. !n the end* we calculate the average time in the main loop and print it on the screen. 'verage time is calculated #y dividing the total time to total customer. NN print the final average wait time. dou#le avg)ait J 1totalTimeF1.03 N countC cout KK VTotal time0 V KK totalTime KK endlC cout KK ;&ustomer0 V KK count KK endlC cout KK V'verage wait0 V KK avg)ait KK endlC +ou may #e thinking that the complete picture of simulation is not visi#le. 7ow will we run this simulation9 'nother important tool in the simulation is animation. +ou have seen the animation of traffic. &ars are moving and stopping on the signals. Signals are turning into red* green and yellow. +ou can easily understand from the animation. !f the animation is com#ined with the simulation* it is easily understood. )e have an animated tool here that shows the animation of the events. ' programmer can see the animation of the #ank simulation. )ith the help of this animation* you can #etter understand the simulation. !n this animation* you can see the Entrance of the customers* four tellers* priority Page 10$ of 103

Elementary Data Structures .ueue and the E5it. The customers enter the .ueue and as the tellers are free. They go to the teller straight. &ustomer &1K30* 10T enters the #ank. The customer &1 enters after 30 mins and he needs 10 mins for the transaction. 7e goes to the teller 1. Then customer &$ enters the #ank and goes to teller $. )hen the transaction ends* the customer leaves the #ank. )hen tellers are not free* customer will wait in the .ueue. !n the event priority .ueue* we have different events. The entries in the priority .ueue are like arr, 56 1arrival event at DB min3 or J1, 40 1event in .1 at Q0 min3 etc. (et4s see the statistics when a customer leaves the #ank. 't e5it* you see the customer leaving the #ank as &1 KBQ* 3TKDD* 3T* it means that the customer &1 enters the #ank at BQ mins and re.uires 3 mins for his transaction. 7e goes to the teller = #ut the teller is not free* so the customer has to wait in the .ueue. 7e leaves the #ank at DD mins. This course is not a#out the animation or simulation. )e will solve the pro#lems* using different data structures. 'lthough with the help of simulation and animation* you can have a real sketch of the pro#lem.

Page 103 of 103

Potrebbero piacerti anche