0% found this document useful (0 votes)
690 views85 pages

DST Nirali Publication

Uploaded by

Aditya Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
690 views85 pages

DST Nirali Publication

Uploaded by

Aditya Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 85
; i S i | Second Year (S.E) Degree Course In Computer Engineering | Semester 3 MRS. ANAGHA JAYESH PATIL DR. NILESH MADHUKAR PATIL ® www pragationline.com Gi facebook.com/niralibooks RAKASHAN fener © @nirali.prat ‘A TEXT BOOK OF DATA STRUCTURES FOR SEMESTER - Ill S.E. DEGREE COURSES IN COMPUTER ENGINEERING (CODE - CSC303) As Per Revised Syllabus of UNIVERSITY OF MUMBAI, MUMBAI Choice Based Credit and Grading System w.e.f. Academic Year 2020-2021 Mrs. Anagha Jayesh Patil Dr. Nilesh Madhukar Patil M.E. Computer Ph.D., (Comp. Engg.) Assistant professor, IT Dept. Assistant professor, IT Dept. Vidyavardini’s college of Engg. and Tech, Fr. Conceicao Rodrigues College of Engg. Vasai (W) Bandra win sve 103 uojenuouyengyt1o3dS Price % 200.00 AdOS NIRALI RAKASHAN N6038) SYLLABUS Chapter 1 : Introduction to Data Structures 02 Hours + Introduction to Data Structures, Concept of ADT, Types of Data Structures-Linear and Nonlinear, Operations on Data Structures. Chapter 2 : Stack and Queues 08 Hours + Introduction, ADT of Stack, Operations on Stack, Array Implementation of Stack, Applications of Stack-Well form-ness of Parenthesis, Infix to Postfix Conversion and Postfix Evaluation, Recursion. * Introduction, ADT of Queue, Operations on Queue, Array Implementation of Queue, Types of Queue-Circular Queue, Priority Queue, Introduction of Double Ended Queue, Applications of Queue. Chapter 3 : Linked List 09 Hours * Introduction, Representation of Linked List, Linked List v/s Array, Types of Linked List - Singly Linked List, Circular Linked List, Doubly Linked List, Operations on Singly Linked List and Doubly Linked List, Stack and Queue using Singly Linked List, Singly Linked List Application-Polynomial Representation and Addition. Chapter 4: Trees 10 Hours + Introduction, Tree Terminologies, Binary Tree, Binary Tree Representation, Types of Binary Tree, Binary Tree Traversals, Binary Search Tree, Operations on Binary Search Tree, Applications of Binary Tree-Expression Tree, Huffman Encoding, Search Trees-AVL, rotations in AVL Tree, operations on AVL Tree, Introduction of B Tree, B+ Tree. Chapter 5 : Graphs 04 Hours * Introduction, Graph Terminologies, Representation of Graph, Graph Traversals-Depth First Search (OFS) and Breadth First Search (BFS), Graph Application-Topological Sorting. Chapter 6 : Searching Techniques 03 Hours © Linear Search, Binary Search, Hashing-Concept, Hash Functions, Collision resolution Techniques. CONTENTS Chapter-1 Introduction to Data Structures 1.1. Introduction to Data Structures 1.2 Concept of Abstract Data Type (ADT) 1.3. Types of Data Structures — Linear and Non Linear 1.4 Operations on Data Structures + Review Exercise © References Chapter -2 Stack and Queues 2.1. Introduction to Stack Data Structures 2.2. Abstract Data Type (ADT) 23. ADT of Stack and Operations on Stack 24 Array Implementation of Stack 25. Applications of Stack 2.6 Introduction to Queue Data Structures 2.7 ADT of Queue and Operations on Queue 28 Array Implementation of Queue 29 Types of Queues 2.10 Applications of Queues © Review Exercise * References Chapter-3 Linked List 3.1. Introduction to Linked List 3.2 _ Representation of Linked Lists 33° Linked List Vs Array 34. Types of Linked Lists - Singly Linked Lists, Doubly Linked Lists and Circular Linked Lists 35 Linked List Implementation of Stack 3.6 Linked List Implementation of Queue 3.7 Applications of Linked Lists «Review Exercise * References 11-15 1 13 13 14 14 15 21-228 24 24 22 2.2 25 2.13 2.13 214 247 2.24 2.27 2.28 3.1-3.29 a1 32 32 3.2 3.15 3.18 3.25 3.28 3.29 Chapter -4 Trees a 42 43 44 45 46 ar 48 49 Introduction to Trees Binay Tee Threaded Binary Tree Expression Tree Hutfman Encoding AVL Tree Multvay Tree (M-way Tree) 8-Tree B+ Tree 410 Splay Tree Review Exercise References Chapter-5 Graphs sa 52 53 s4 ss 56 Introduction to Graphs Graph Terminologies Transitive Closure of graph Representation of Graph Graph Traversal ‘Graph Application ~ Topological Sorting Review Exercise References Hashing Collision Resolution Review Exercise References 41-466 4 42 424 431 433 438 450 451 458 461 464 486 54-5.5 51 52 54 54 56 52 513 sas 61-615 61 64 66 613 615 ean Chapter 1 INTRODUCTION TO DATA STRUCTURES “SYLLABUS ‘© ‘invoducton to Data Structures, Concept of ADT, Types of Data Structures - near and Non Une Bata Souctses, _Qperatons on Daa Site. ‘CONTENT 1.1 Invoduetion to Data Stucures 112 Concept of Absact Data Type (ADT) 13 Typer of Data Structures = Linear and Non near 14 Operaticns on Data Stctures Review Eercse References {INTRODUCTION TO DATASTRUCTURES || * tres: Hover of eps wen aor sos Characters ofan a ‘ata sclence and Data Anas are emering Fils in the word todsy, These Feld equi data processing. ‘ata procesing can be dene only if we have data stored in any format So itis important to store the at, Data ar colection of fects oe values in parr format. Tere ar cferent posse ways to store the axa depending upon the application andthe way data want 10 be retrieved. Thus we have diferent Oata Stuctures, Data Suuctues atows us to perform ‘rious operations on dita, Based on which type of ‘operation i requied, we can selec the Data Structure. In this chapter, we are going to iscuss ferent data structures and algorithms which seve as buling blocks for increasing efficiency cf programs ‘An algartim te 0 set of single Instant to be [ellowed to solv a protler. ‘A welidefined algorithm abrays provide an answer and is guaranteed to terminate For every algorit, it Isimporant to find out the esourced required suchas time or space rithm a Input The algorithm must accept 20 or more input. Output The algorithm must produce atleast one output + Detnteness Each sep of lgorthm must be clear and curambigueus. + Meciveness Every step must be base and esses Control structures used in algorithm are: 1 Sequence: Each step ofan algo is erected in 2 specie order 1+ Decision: Execution of 2 process depends on the outcome of ome condition (then ee) ‘+ Rapetton volves executing one or more sept fo numberof times. (while, do-whie and for oops) amples of algorithm: Algorithm for swapping to values ‘input Rt mamber ae A 2 input second number st 8 2 SerTemp = A Asea=8 S.Set8= Temp Granta 2.6N0 ‘Aoi fr pring fist 10 natura umes tite) serie, ne10 2.Repeat steps 3 and 4whileie=n DATA STRUCTURES (5 Comput) 02 INTRODUCTION TO DATA STRUCTURES Sram 1) and fare the functions dened on» poste Asetietoy Integer ube then fo) = OI Le of nis age lend otto) (of g of ni and ony if postive constants ¢ andy tno. ‘exit such that fo) <= cg means Bat fr Ine ‘port anata + To anayze any algortnm. the requirement of the resources sich as time and memorfspace should be ‘ambfed duringexeouson. Then we cn pret New ‘much efdent an algrthm would be. Eeney oF Comglesty ofan algorithm sted in ter of tine and pace compleciy. also igortm focus on ‘computation of space comple and tine compen. 1+ The time complet ofan sigorth i the rening tine ofa program at funcion ofthe input se. The space complesty of an algonthm i the amount of computer memery that required daring the program ‘erection asa fncon othe input se Space compleiy specie space required to store rogram and dat i any during execvion of the rogram, Generally, the space needed bya program {depends onthe static and ymamic pr requrement. Time complet species the time required to excite program the number of instructions whch rogram exeaites It ako called as runing time oF ‘computing tine comple Nemaly time comply depends onthe sce of the input Sa we eon have: > Best Case running time: This i the optimal condition. > Worst case running time: This denotes the worst possible ase of the input sequence. Average case runing time: Tis denotes runing Sime of average input sequence General, the quantity required isthe wors=egnh when >=, ig ©: Theta notation provides an asymptotic tight ound ort 4) = OA) If and ony fe) = OANA anf) = ‘ev. 41.1.2 Need and significance of Data Structures (Define Data Soucture: Mays ‘A data severe is basicaly 0 group of deta elements thot are put tgeter under one name, and which fies 0 porter way of string and argon dat ‘acomputermemoy shat can be ued een Data structures canbe thought a conceot where an algorithm or set of algorithms ae uted to struct he corded datafnformation while string, These Algorithms can be implemented in any programing Tanguage. Widely used among them are C Ce, 4a, Net Python ete. When we choote programing language like’ or Cvs, we need to write code for these algorithms whereas languages such a ava and Net have colection famework wate predefined implementaions for dierent data stuctues. are proved ‘ata stares ave used in skmost every program oF software sjstem. Thay seve 3s blag Socks of 9 Program A program bull uting improper data strucures may not work as expected. So. as Programmer it Is mandatory to choose most appropiate data stcwres for a program. Grery Signa program wil ue on/tome data srvctures) ‘eit For eg. A stack Is Imply used in a DATA sraucTURES (Comput) on common examples of dts structures are array, inked Tis, queves stacks bay trees, nd hash abe. ‘ata sutures ae widely apie in the flowing ares Compl eign ‘perting stem ite nai ‘Databae Management Systems Numeric anase Simulaton| ‘ri inteigence raphis Sei Networking Data Sence fz eee ESAT ‘| {bophin aor. Dee-17, May 18 ‘+ Data Type & the sot of var that the vate can fake. Ep Ine char, lat, double. Abstoct means ‘considered apan fom the dete specatins or implementation An abstract datatype (ADM ia ett ‘operations inespectve of how the st cf operations Implmented ADT is the woy we lok ota Data Sucre: the oly focus on what ht Dota Stcure dos end igraing Dow it doe tsb, Examples of ADT: Suck Ques, oc mange mn we 4 eae fe at Sout be dec one a0 Garied out but wth type of date aed ooaciecs Se be performed on t [L3_ TYPES OF DATA STRUCTURES 1@ Explain diffrent types of deta structs we eample. noe on bn ety BE aerare wt 7 a fie 0 in € Abaact Oats Typet ‘escigton of the data 18 ‘perations thet can be pertrind sactaiee regard a Tetucr on mw ome Map ery Data Structure stores the Sasi aspect my 2 acess and ute data efit. Ang tt cn cre the data canbe caled as a Data Structure. Dota roms such af letege, Float Boolean. Character Sore = vaable/dat, pence they are also Daw Struma Drimive data type indicates buik-infundamera! xs ‘ypes supported by 3 programming lnnguage. Soce ‘hese are pte ata typen ey are known 2s Prime Daa Stuctares. We ako have Dam Stucues out store large ‘conmected data such a5 Array, Stack Queue, Linked is, Tees and Graph Since these Dat Structures are ef by user, and are crated sing primitive data SECU, they are called as NonPrinitie Dats Srucaes, Daw seucnee 4, Pine Data Sructes (@uitin Data stucutesincates memory locaton which an hed single value) Integer Fost Non-rinitve Osta Stuctures (User Defined Daa Severs) (Charcer Double Pointer UnearDaStuctares_NonUnea Data Sucre ‘Sequents (Pande) Arrays Stuck Queve Unked Tres Graphs tat Figure 1 Types of Data Structures ‘+ tase on the diferent charac, Data Stuerrer fn be futher cssfed. Into Uneton ines, Dynami Data Structures {13.1 Linear and Non Linear Data Structures HomogeneousNen-Homogentost and Stat) | © Bxplaln Unear and Non-linear data structures Dec19. Ma > i snropUCTION TO DATA STRUCTURES ATA STRUCTURES (St Compete ro INTROBUCTON To DATA srivcuRIS camasmicas ano 1 ton nerf tao te Selman cet Pee Set Os Scere ‘nnn a 2 «fri oc oy kone Un storie aru seine 8 eo 071 revo een enon ty es tren nap eer Se, sequel memory lations. The oer way & tht ‘Figo RSI ate elements sng tein + In Non-Unear Oat Seuctures, the erfeements 3% not stored in 9 Hnearequential mann. The elements arent ajacent each hs Eg. Gap. Tres 132” Homogeneous ond Non-Homogencous Data Structures 2 + Homapensous incates all the daa Ree/lements are of same ype Eg. Amay In Non Homagentous eta Seucures the elements may or may rt be of ‘be sar ype. Ep Stctues 133 Statle and Dynamic Data Structures + [se and he sata associated memory locations Sr fed at compie tne, igh Data Secures ae cated as Sa Data Seuctre] Eo. Ary. Whereas cena Oat Scares may ask f_evand [E42 OPERATIONS ON DATA STRUCTURES _| 1. What ore varius operations possible on Data Stvctures Dec8 Felling are the base operations which are possible on nora Data Sucre > Inert an element - adtion ofa new data element inadstascure, > Delete an element - removal ofa data element ‘roma data srvctreifts found > Seach an element - searching for the specified data elementina data structure. > Traversal ~ procesing all the data elemens, presertin > Sorting - Aranging dat elements of 2 dats structure ina specfed order, > Merging - Combining elements of two similar data “srectures to form 2 new cata seucure of the same ype, [REVIEW BcERCISE ‘Multiple Choice Questions 1. Term ata Stucure refers to aed lnterlaorship between ther. GY Organization of data element 0 Array fect ones at certain tems maybe processed? (0) nsering (©) Trovesing (© Deleting (@ Seating (Aes. ) Wich fe folowing non inesdata strate? (0) Tee () Suck (@ Arey (@ Unked us amt) Wich of the folowing & not 2 primitive ota sweue? (0 oieon ©) ieger (© Ourocer z 2 os. coy | 5 Descriptive Questions Define Asymptotic notations. Esplin diferent types of ata sructres with example. Mays Define Data Structure Diferentate between Foes and rnominga data structures. Deed Esplin static and dae dat structures, st diferent apotiations of data structures « 7 a 2% n. 5. Which ofthe flowing operations access each ecard | 6 What are the vaous operons pose on dna Drc-it SK Sthastna Deepal Serine: Dea 5 Through C BFB Publeation, 2nd sd Rv aon. i Yedda Langsam Mosh) Augen, Aeon “Tanenbaur Data Suuctses Using C& Coe, 1556 ition. Reema Thar: Daa Stucures Using C Odont Univesity Press, dd Eaton 2016 |SRO Grou: Data Structures sing CTH, dd 21. Witesh Gupte: Dats Stucure Using ‘C, ttematora Book House Pvt Lid, 15 Eon 2012 epsyPwnengtlacin heps/fopendansructuresory Inapsiwencounen.on pein atpeintcon/dee uct asl 10. hres gatevdyaby construc! naps sanfounaycom dependig 2 FEE | 0) coding sandons wom teat Beare | ee aad se Bre caled as Dynamic Buta Stvetures)| (8) Progremming Language Statement (Ans. (8) ee) ae +S pierce beoreen Tinea? imar Dats |) Peectnfomation Sener (©) Bunchafinfoation (© None of here near Now-Unear (@ Progaming statement ns.) Data Smoctre ata Soucturs || 3. A0Tis cad as Abtact because Inte Oats Sowers, | in Noting ut, (a) None of hese the lemens arestredin |Sructures he elements | | ©) Riscomplete independent data ype sequent manne, aenatsodina (© Riscotecion of tert data pes sequen manne. @ Iplementaton Deis are hidden (ans. (4) The tense! Thereatonshp of 4 Operatinson data structures ae sceneytsminained | agaceney ot (0) Seareing beeen elements alte’ beter 0 Taig (6 sean tan element gegen as = (2 Deletion of eemeot 2 <[s.tee G (©) Allott above araten Chapter 2 STACK AND QUEUES S¥LLABUS {& ‘introduction ADT of Stack Operatns on Stack, Asay Implementation of Siac, Applications of Stack — Well form nes of Ptentheris Ife o Post Conversion and Post luaton Recursion {Induction ADT of Queue, Operations on Quewe. Ar Queue 21 noduetion to Stack Data Strtres 22 Absvact Ost Type (ADT) 23 ADT of Stack nd Operations on Sack 24 Aray implementation of Stack 25 Appleatons of Stack 26 Invoduction to Queve Data Stuctres 27 ADT of Queve and Operations on Queue 28 Aray Implementation f Queue 28 Types of Queues 210 Appcavons of Queues Review Exercise References Bi INTRODUCTION TO STACK BATA STRUCTURES + [eset ine te re ih eect “eco ete cane partorme nee «Ths en inwn ay Topatie stck Sete at then de th Sk woud bee reer foe detea Sch so aed yt fF Oat {tro sce Top Figure 2.1 General presentation of Stack ay Implementation of Queve, Types of Queve ~ Crevlor Ireduton to Doubs Ended Queve,Applcaors of HEME nen ~ConTENT "+ stacks can be best explained by considering an ‘example of Stack of dshes where the mest receniy «added doh can be removed fst andthe fist dish can be removed atthe end [22 ABSTRACT DATA TYPE ‘+ Data Type isthe set of values that the variable can tale. £9 Int char, float double, Abstact means Considered ape from the dead epecfeatons or implementaton(an abstract datatype (ADT ia st of ‘operation respective cf how the st of operations is implemented) ADT ls the way we lok at © Date Structure the only {focus on wt thot Oot Structure does and ignring owt det it pb ‘Examples of ADTs: Stack Queves. SR ee nee este eer a DATA STRUCTURES (St Compute) 22 + In Abstract Osta Types can be thought of as 2 description ofthe dta in that the stucure with 9 Est of operations that canbe performed onthe data within the stature without reir tots implementation. 4+ For eample, when we wea stack ora queue the user is not concemed about the detit of how the ‘operations ae cared out but with type of data and ‘operations that cn be performed on [2.3 ADT OF STACK AND OPERATIONS ON STACK srAcKe queues ‘would display D here. Pop opention i cle, D would be deleted and Top would be decremented by ‘one as shown in Fig. 23. Top afc OPA par Bera as) wae ae Figure 2.3 Stack ater Pop operation 23.1 Amy (Explain ADT for Stack ‘The Stack tan abstract data type. The fundamentals operations ona Stack are: PUSH inget an element. FOP delete the mst recent iseted element PEEK splay an element the Top ‘+ "Wishes are input operations and Pops and Peep are ‘utput operations. A Pop ot Pek on an empty stack considered an eror inthe stack ADT a5 thee is no clement inside it However performing Push on fll stack not condidredas an ern the stack ADT. ‘Stacks can be implemented using arays or inked ts. Figure 22 represen the avay implementation of 2 stack ater several operations. Every sack Wil Nive two vibes assodated with it Top and Max. Variable Top stores the address ofthe topmaat iment ofthe stack td isthe only visible element. Max is wed to store ‘the maximum numberof elements thatthe stack can IF Top = Mate then the stack is fl and i Top = | _NULL thn the stackis emp. Top e[clo ores 45s 678 9 Figure 22 implementation of Stack using Array This gure shows @ Stack having Max = 10 and Top = 3. Top = 3 indicates there are 4 eerenis inthe Stack Le. Push operations ate done, For every Push, ‘op would be incremented by one. Peek operation + An ory & 0 callecion of tinier daa elmer ‘meaning the elements hovng the some dat pe The elements of the aray ae stored in conigueus rmerery locations and are referenced by an index. ‘ata Structure Aay wil be used when we want 10 store the simlar typeof at. In the ante sed fr array dedaratonis Datatype Aranamelsie 3. i O15 ‘+ This wil dette an array 10 that contains 5 elements ‘As we are aware ofthe aray index aways stars rm zero. This means thatthe aray ID wil contin on § ements with the index staring from Oto 4. The fist lement wil be stored at IO(] s4cond element at TDIM, so on and the last element, that isthe 5° element, will be stored in IDI. The memory represetation for the ary ID can be shown 38 in Fg.22. ‘001 [002 [003 [oos Toos } TOF} 201} 10} 101) 10H) Figure 24 Memory representation of aay 15) ‘Implementation of arays is very ean dsp of his there are cerainKmitaons fr ths Data Stuctre which can be listed as flows: > Fed Sz > Contiguous memery acatons may nat b anys salable > Inserion and deletion of ements an be problematic [2:4 ARRAY IMPLEMENTATION OF STACK 1 Write an algorithm for implementing stack wn stack e qutues ax, ara STRUCTURES Com 1 Awe kno, Suck hs vee base operations Push pop and Pek Lt ook Row these tre operations can be paformed ung ry. Push operation: + Push operation is used o Inset an element into the stack, The new sement i added at the topmost prstion ofthe stack where Topi caren pointing core iverng new element we must check whet ‘the stack i fl Le I Top « Mt? if yes, then we aot inser any element athe stack. An attempt Inger an element inthe fll stack woud cause STACK ‘OVERFLOW. Loot athe stack shown a Fig 24, stack sirexdy has elements hovig Top plating a poston Land Mac 9. ife want net 9 new eement Ea {hs stack we fest ehck Top » Mast. The cordon {stole 10 we erent the value of Top Top wll now ont at 4 and store the new element a the postion (ven by stacToph. Thus, E would be Inserted at ositon4Fip.25 nates updated stack, ep GieTeTo ot? aes 67 8 9 Figure 24 Stack having 4 elements Top + ATsTcTove ore2aaseres Figure 25 Stack after Push operation IF Top = Ms PRINT STACK OVERFLOW” sores 2SETT0p «Tope 2:SET STACETop] « VALUE 400 op Operation: ‘+ Pop operation ls used to delete an element fom the sack The topmost elements deleted Le the element here Top is erent porting wil be deleted, Detore ack is empty? Le, ls Top = Null If ye, then we ‘ono eave ay element nthe tack ati empty, ‘an atempt to remove a0 element fiom the empty sack would cause STACK UNDERFLOM. Look at the Steck shown In Fig 24, stack aeady has 4 elements fing Top pining at postion 3 and Max = 8. we vant to delete an element fom this slack we fist ‘heck Top = Nul The condtion Is fale, 30 we can elt the vale of Top ge by stackTop 9 well as ‘is value wil be retued Le. D. Alter every Pop ‘operon Top has to be decremented 10. point topmest element. 50 Top wil now point at postion 2 Fig, 26 ndcates updated stack. tp 4 [ele ore? ses 67 8 8 Figure 26 Suck aftr Pop0 operation thm for Pop operation: TF Top = Nol PRINT “STACK UNDERFLOW o104 2 SET Valve STACKTop) 3 SET Top» Tope 1+ Peek operation retuns the topmost element of the Stack Ths operaton does not delete the topmost lement nd hence poston of Top resins same Peek operation ako checks whether the stack is empty Lets Top © Nu f No, ten the value I retuned, Peek operation scaled onthe tek gen In Fg. 24 would be retuned ‘Algorithm fr Peek) operation: Top Null PRINT “STACK UNDERFLOW" oro, 2 RETURN STACK(Top) BEN ‘Program for implementation of tack using aray: {Wa program in‘! fr Implamenting Stack ug calng Pop operation, we mut check wheter the ‘Array, DATA STRUCTURES (St Com a, sucka comes incade etoh> fndude sibh> deine mux se instackina se opt veld ih: vei oe vel pest vei pls immsing ( Intopion eo i plage rrstacns inselect anyone fhe allowing options: Pent Pu print Pops pin Pek: Pins ily pens 5 6, Pr Enter youre esl open suiteoptind i push break 2 ono break: ese, ek break: case splays break + ase» deta: prt ninvald chee whileloptont=Se retun ) oid push ' sn rome IMtope trax sie-1) ‘ print stack Oven): Int tem = acto topes rintfe\iThe popped element item: ’ , void peg ( eopee-t) 1 rin Stack Undertow: ’ che ( Int item staktop Drnt\aThetopmast elements der ’ ) stack queues pa sraveruts tomo) 8) ene fe flowing ops eid pad int rindcaThe stack elements are: fortstopi>=0- ( pines: rose i ‘etc anyone of he folowing options: japan arop ‘1Peek mer your ehie Ener the data 10 ea Saletan one ofthe folowing options Ph Fo» a1 Peek ‘1Dipley seit Ener your choice :1 Emer the data :20 sesTacase sel a1Pah 21Pop 31 Peek ‘90g geet Enter your chole:3¢ ‘Thetoprost element 20 sistas . “select any oe of the folowing options: span 2170» 3 Peek ‘aDipay syest mer your choice 2 “Th popped elements 20 ieeteore! “Selec anyone ofthe fling options: Ph 21Pop 3) Peek ‘3 Dispy sleet Ener yourehoe Some ofthe applatins of stack that we wil dca ae 1. Reversal ofa sting, 2 chectng val ofan expression containing ested we xeon, 4. function es Recursion, 25.1 Reversal ofa Sting +A sock i» date stractve In wih lems an be Inseted on) from one end and get iems back fom the same end. Therefore, the lst em inserted nto sack ithe fist tem tobe taken out frm the stack In sorts to ale Last a Fiat Out UFO), ao sracc a qucvis SATA saveTuns1stCompume) _g@)_SIMRQUETS, 1 tn teversal of a sing, the idea isto create an empty stack and push ll characters ofthe sng to Ie Then. ‘we pop each character ane by one from the stack and put them bac othe input sung stating fom the OP @ a aff A ofa a ee fete etaete & Feeeee foe 414 8 BE jt una owns (Program fr Reversing a Sting using Stack ‘indude include ctingh> ‘efine MAX 100 ‘Pmasimum noo haractes'/ Pstackvaibles/ intope-t: intten: Feat 7 ‘Pscing declaration? char stack sng NAN: ‘Phnction to push character tem/ od pushcharchar tem: ‘Phaeton to pp characte (tem)/ ‘har popcharvoid ‘Punetion to check stacks empty or no'7 inestmproa ‘Phuneon to check stacks fll ornet/ Int Fu Int raing cl har sea inet pandinputa sing: scan HINO} a7 ead sing with spaces") (ett - cudeceioh> Prcudecsvingh> een X20 sever sack fi char san int to: is eid puscharitem) (stop «= g4ax-1) print (Stack Full: he ‘ ‘op » 0p» :// Push the cha and increment top ATA STRUCTURES (5 Compute a sack w queves ss (top er rind HUNBALALICED EXPRESSION: , bree , ' ri ’ veld pop Wer a‘ ( t top 22-1) coy ( pind (Sacks Emery: , che ‘ ‘top = stop -1:/ Pop the car ad decrement top , ) int rnsing Pie(VINPUT THE EXPRESSION "5 sanie%s" ep font = 0} lfc enresions are readoble and sokable by humans becuse of eal dsingushabe ore of pets, bu comple doesnt have integrated de of pent > Hence to soe the Inc Epresion compl wl sean the expresion mute tines to soe the fub-espesins in expestions ode which i espe. > To mid this tavening, Int eresons ae comened Poti epresion belo etion Algerie step 1: Scan he Inf Expession om fog. Step 2 the scanned characte: i an operand, append it th fal nit Postfix ting Step 3:5, Sap 21: If the precedence order of the scanned coming) operators grestr than the precedence order ofthe operator inthe stack or the stack i empty or the stackcomtna Cor Ter" pushiton stack. ‘Step 32: Ee, Pop al the operators frm the stack which ae grater than o equa tin precedence than that fhe sanned opera. After doing that Push the senned ‘operator tothe stack you encounter parenthesis while Popping then stop there and push the scanned opestr in the stack) Step 4:1 the xanned character isan‘ ot ot‘, push wthesad Step $f the scanned character i an Yor of, pop the ck and output it unt a or! or respectely is ‘encountered and discard bth the parents. Step 6 Repeat steps 2-6 ntl nic eresson scanned Step 7: Pint he eutout ‘Step Pop and output rom the stack untl ts not empty. example: table 21 below. Table 21 Polish Notations eters | rete renin [ ots epson laswre Jreasc _|avece [asm-cso reaneco [asco Iheseeno cance |asceso- [asa-cyreo-en [/earecncron [ae = coer) lesbrenaery —(rdaeran Invnc-ove —_[over-sera — |ueo-oty Convert *(8 +€)*D to posi nctation, DATASTRUCTUNIS GECompu) __gao _sraccmquevs ‘Curent Token Mowe Stack 1 10 Note: 1+ Inthis abe, te stack grows toward the left Ths, the top ofthe tack sthelefmost yo, ‘Im move 3, the left parenthesis was pushed without popping the * Beaute had lower piety then °C In move 5, "+" was pushed without poping °C because you never pop let parenthesis nl you get amincoming right paretnei In other words ther it 2 dstincion between incoming pity, whic is vey high for 8, ad inetac priory, which flower than any operator, 1+ In move 7, the incoming right parentesicaused the “e" and "C10 be popped but ent the “+” at writen out ‘+ levmove 8 the curent had euslpronty tothe fan the stack So the “onthe stack was popped. and the incoming “* ws pushed onto the stack Program for Converting Inf Expression to Postfix xpresson ©. write » Program to conver Inf expression to postfix expresion. ee) ncudecstion> har stac205 Inttop «1: veld pushchars) i stach( stop] =e 1 ‘arpon0 ‘ Meap ==-1) eum ese rum stcttop-t: , In porierars) carrer Print Ree ebeite=="0 pubes eseitte== 0) i while popO) = 0) ri ) te \witoroninstactopD > prince inte pondt | pushes ) DATA STRUCTURES GE Comput) ' whtetop =) ‘ prin etpor ’ remot i ‘ourur ner th expression z Av @C-DIA) poco Emer the eorenion (arbree acrdety 2 Postfix Evaluation J once an expression has Been converted to post retain, it i evuated sng 2 stack to store the pends The sep to eluate the posi expreson areas folows 1. Step through the expesson from let right ‘etn one token ata te, 12 Wherever the token [5 an operand stack the ‘operand inthe ode encourtered 2 When an operators encountered: ‘© I the operator it bin, then pop the stack 19 the pert ie unay (eg uray minus pop Perm tended operation on te operators. 2 Push the resi bacon the stack [A the end ofthe expression, the top ofthe stack wil have he comet value forthe expression example: Euate the expesion 23.4.6 ‘Move | Curren Token | Stack grows toward lf) 2 2 3 32 4 432 2 7 5 514 a 70 2 2 5 6 7 stack 8 queuts Note: Move &: An operator is encountered, 50 4 popped, summed, hen puted backonto stack, «More 5: eperatr * ie cnet token 50 7 and 2 are oped, multe, pushed back onto sack, + Move 7stcktop hold corect aut ote that the posi notation has Been created to properly velect operator precedence. Thus post apresionsneverneed partes Program te Braluste the Postfix Expression ‘a. Wate a Program n'C'to evaluate postfix expression ‘sig Stack ADT. (May 18) 3a incudecstdoho Inesaleoy Inctop = od pushed i stac( 0p] 2 , ine pond fi eum sactop ’ inemaind ‘ hare: eure inentxdram inden the expression = seal ero ier e = 10) ( stgucen um = 4-48; puskumt 1 —™ DATA STRUCTURES SE Compute ay stack queues ese 25.4 Recursion ‘ Recursion i a procetin which a problem i deine 1 = popt terms of Asell nC itis pole to cl 2 friction 2 = pop ftom sel, Functions that al themselves are krown 35 Reet recursive functions Ge 2 satement within the Body of 1 function cal the same function, Recunion is often termed 2s ‘Orculae Definon”. Tus recuson ts the proces of defing something In terms of ist. To Implement recursion technique in programming. 3 funtion shouldbe capable of callg set break Earle , id mang case i ‘ Some statements") 3 «n2-nt; unto: breaie cnn Some statements 7 ) , case vei unto i fi bent Some statements "7 bree fu: RECURSIVE CALL? , anne Some statements 7 casey: , i ‘+ Here the function funt@ i ang isl inside its own eee function body, 50 fund is 2 recursive function. When u main cls und the code of fant wil be executed os and since there is 2 call to funid inside funi0, again ) funtg wil be exeate. looks tke the above program , wen up inet times, but general a terminating peshn3): condition is writen inside the recurve functions ) ’ prin(\rthe result ef exesson Rs = e\niwiexp, een tum; , out: Enter the expression = 2346°5* ‘The suit of expresion 2346 wich end tis reersion, “We have seen that recurve calls execute lke normal funcion cals, so there no eta technique to Implement recusion, Al function lle (wheter Recursive or Non Recushe) ar implemented though rn te stack Stack is @ Last In Fest Out (UFO) dots structure Ths means thatthe lstitem tobe stored on the stack PUSH Operation) the fst one which wil bbe deleted (PO Operation) from the stack Stack stores Activation Recordi) of function during rn time, Here we wil tke the example of function fact ‘we have seen in the previous recurve program to find {acral ofa number, srace a ques masons ue a a eee p ee Le ammo cerntey cement yen sa earranmn tie a ee re evaluation of factoral of 3. pointer is 3. Peek would Gisplay A the element to Front Rew (aah [tom 7 which the Front ts currently pointing Wf 2 Dequeve Taxeant] eee ceaseetesament tet Sours x aaa | [orem oe Sse anaenesemes | * Tween |? [anertecen |? [anortaan se snown in figure 210. Figure 2.12 Queue after Enqueve(® operation que) GEESH [Race] [ene a ‘ AR ot fact) CteleTo i} 7 |. feos aes eee | macs] [acme] [atmo acne aise A a enter was eeeea ta teen ter « || __EitsEIaesawst nai -_ [Null the queue is empty. FSET QUEUE[Read = Value De ee es aera iaeeitee ace neece pa So os neo “+ Fest mang i clad. s0 PUSH AR of mung into the | 7 ADT OF QUEUE AND OPERATIONS ON ‘+ Queue has two basic operations Enqueve, Oequeve. |» Dequeve operation deletes and retums the we earn eran * mete leen seers eae aera meee sper e | ese ee Sinema aaecae sede pesos plas Saath sonore ack Ubewee PUSH AB of fac), Aer hen fac complete, POP AR of tc) Saat, ahr cempleson of 2 sce funcion POP its coresponding AR So when mind i completed POP ‘Ak ofmand, Now sacks emo + Ime mincing phase te sack content Increase a Inne Acoation RecoriAR) are crated and pushed iro the act for each vocation ofthe hein In the unveding phase the ciation Records are poppe tam te stack in UFO order te eigina! im a TO QUEVEDATA | +A queue 0 near de sacre in whch nsrion neat ere end wheres deletion i permed othe ‘er end 1 Adin ofa element inte que can be dove rom the end cled Rew and the element ca be removed {rom the cer end cad Front Since the seant tat ‘8 inser fst would be te element to be taken out fest a queue 1 aso ead Fiat In Fost Out FO) ‘+ Queves can be best expaned by conideing an > Enqueve- near an eament at the end of the shea. > Dequeve - delete (and retu) the element a he sta of te ist rend. > Peok= display an lent a te Fron. Front fear 4 4 aTele[o o123s4s ‘Figure 29 General representation ofa que, “+ Queues canbe aso implemented sing ether aay linked ss Figure 28 represents aay iglementation of queve ater several operon. Every queue hat ‘te variables ont andre that point othe peston from where dletons and insertions can be done especie. Tid vale, Mari used to store the ‘maximum rumber of elements thatthe queue can sor + The figure 29 inccaes 4 elements ae inserted inthe ueue A the fst element added to the queue then 81 Cand D ung 4 subsequent Enqueve operations aro 016 que tr bus wter the panen hos | seers every tnqueue operation ‘Rewr rooer iJ + Enqueve operation Increments the Rear pointer and Inserts an element inthe queue where Reariscurenty pointing. Howevet, before inserting an element in 8 ut, we must check for overfow condition ke to ‘hack wheter we are tying to ingen element int 8 ‘queue that is abeady ful The overflow condton for ‘que i given by Rear = Max 1 + Fig. 217 depicts 2 queve having 4 elements. Front pointing at inde 0 and Reais ping at index 3 and Mac = 6.1 Enqueue( is ale, Overow contin ‘hacked. Since condition i fale, we can insert an ‘dementia the queue. Rear would be incremented by fone, hence wil point at index 4 And E would be Inserted Fig. 212 shows the updated queue Front eat coro opengraimisienes! Figure 2.11 Queue having 4 elements ready ematy? Front» =1 and Rear 2 queue that = 71 means thatthe queue is empty. there no ‘eementin the queue 1 tte by to delete an element rom the queve ven in Fig 211 Fronts caren Underfow condition wil be checked fst Since the conditon 1 Fe. we ene MAX'S ei ise by pry: od dete by print wodern, vod eaten: wei in poet: erp Int ont rae weit mang t ener ATA STRUCTURE (5 Comowte om Sra w aves nel iat an tment to quese"E ind r2- Delete an eement hom queues tn} «Olay quae elements {Funcbon to create an empty pronty queue / {Function a nse value to pony queue {7 Funcion to check roy and pace element */ vod cnecnint da) ( me for =i ex aries) ‘ (ena >= peqvetD t for amare ty > ci) ‘ PrLquel = prgue = 1 , ed reo ’ , Pruett = da: , {7 ancien to delete an eement rom queue ‘vos lee by poortyint 33) inet ara SUTIN id epotee BCE TT * spat ocume is evty na sean dete foeG i <> ac ‘ ene == ri esetD ‘ orev ermacies) c Praia = paul + HP , rq = 99, pri not ound in que ts delet’ daa , 17 Fancton to play que semen */ oi play. promsed ‘ ‘on i pene rave semen: ren , 1) gear tp for front «+ rear rontes) ‘ print pr. quran: ’ fron = 0: race oun Enter vale tobe insted $6 enter your enice:3 89 56 45 20 {enter your ehice:2 er value delete 45 rw your choie:3 29 56 20 rer your choice 4 2.9.3 Double Ended Queue (DEQUE) (© Wite a short note on Double Ended Queue, Dxe-19 Dogue pei pe efquve in which the elements can be rare or ler ot bot the ends. ‘+ Remeving the restcton given in near and ciel ‘queue, in this queve elements can be added to oF ‘removed tom ether the front head) or he back (a rd. Hence sao called as Hed-Tall inked at. ut wn cannot add or delete the element rom the mide ——__|_ mrermorntder ate ie semen tom te ride sree queues a ¢ i? eqn as ie A a ‘+m Dequeve, Left and Right pointers are msintained. Dequeue can be Implemented using crear aay. ‘There are wo ype of Deque > Input Resviced Deque in is pe of deque, elon can be done fom both the ends and Insertne canbe done fam one end oy. > Outout Restricted Deque: In this ype of due Ineerons can be dane from both the ends and Queue is wich in CPU scheduling, Disk ‘Scheduling, When mutiple proceses require CPU at the same time. vaous CPU scheduling Sports ae used which are implemented using Queue data structure, > whan datas wastered aymchronousy betwen ‘wo proceses. Que suse for syncronization. ‘ramples: 10 Burs pipes le 10. te. > In pit spooling, documents are loaded into 2 butler and then the primer puls them off the buf a its own rate Spooking ao lets you place 1 umber of print jobs on 2 queue instead of waiting for 240 ane to fish before spectyng the > Breadth Fat search in 8 Graph isan agent for tvensng or searching graph data srutures stars at some arirary nade of # graph and caploes the neighbour nodes fst. before moving to the nest level neighbours. This Aigoritim uses Queue dat stucure > Handing of interupts in realm systems. The Ineerupt ae handled inthe same order 25 they ve fiat come fet served FCS) > Im esl We, Cal Centar phone syste wl se Queues to eld peopeealing then in an ere, Lola see represertave se + In tis section we wil S68 how queue i wed in CPU schedving Ina compute stem thee are arumber (Of process that are presenti ferent states a = partclar te Some processes may be inthe wating Sate, others may bein the aning sate and 50 on ach sate has data seucture cle queue in which stores te process, for earl. witng sate we Ihave waiong queue or ready queve, in ruwing ate wwe have running que, «te CPU uses some kind of proces scheduling algortims to select one procest for ts exciton amongst 0 many processes. The races scheduling algortws are used to maximize (CPU vtkaation by ncensing Brought, We have dierent scheduling sigatims ke 1. Fist Come Fit Seve (FCPS) As the name suggest ‘he proces coming ft in the ready sate wil be exceed fret bythe CPU irespectve f the Bust time ‘or the prorty. This is implemented by using the Ft First Out (FIFO) queve. So, what happens that sen & process enters into the ready state then the PCB of tat proces wil be Inked to te tl of the ‘queue and the CPU sas executing the processes by taking the process tom the head of the queve. if he (GU Gs aloeated to 2 process, then it cant be taken back unt it fishes the execution ofthat process. 2 Shortest Job Fist (SIP: In the FCFS. we saw ita races it having a wer high burt te an it comes fest then the other process with avery low burst time have to wat for its tum So, t0 remove this problem, we come with 2 new approach \e. Shortest Job Fistor Sm 1 ths technique, the process having the minimum bust time at 2 pariclar instant of time wil be ‘executed fist Iisa non-preempive approach iif the process stars fs execution then twill be uly executed and then some other proces wil come. 3. Prlorty Scheduling: In this approach we have # Dronty number asocated wih each process and ‘based on that prionty number the CPU selects one process trom alist of processes. The proty number fan be anything. is just used 10 ienthy which |_prcetunang a hgh pry an wich roses STACK 8 Queues xsasmucruns etcompaeg 028) tcency of ts lgortn toaly dependent on the sy having lowe rity, Fr expe you can denote 0 ine hg pony proces nd 1 1 eet (peony process athe revere can Be Put L& YOU an denote 100 a te highest pty and © 8 he lone por: «4 round Rabin Schebling: The Round robin lgrtion {ea pre-emptive proces scheduling algo Hee, very job request nthe queue i asocited with 2 fed eecton tine called quantum. & preemie proces nates he ob scheduler to pause 2 proces Under encuon and move tote nest proces in he pdqueue For example we ar having thee proces PP and PA and ow te quartum sms then PI wil be given ~ ams forts encom then 2 wil be given 2m then PB wil be gven 2m Aer one yl agen PY wl be jven 2a. then P2 wil be gen Zs and 40 on unt the procenes completes execution tis geney esd inthe time shang environments and ther wl be no tanaton case of he round-robin. The | sheer saves he cent stat ofthe ob and moves to another job in the queve as son a5 8 pariclar procenvob erected for + gran tine quantum. The content itch ves the caret ate of the process. Ti “Saori benecilin er cf response time nthe ‘ound robin algortim ever proces ge an equine of fexecuton whch is Gefined by the quantum time. ‘Therefore no proces wil be able t hold the CPU for longer time ped. The roundvebn job scheduling Algor, hereto sen mt-e e-daing oF rrit-tasing operating ystems As wrest is probably ‘he best scheduling agent in epertng sytem for ésrbuted ternal response Ue Furhermor. the Round robin mand rte ume quantum and the number of Contest Sitch, that cou The fw of round-robin xehedulng 16 own in fire ovo) <1) <> Figure 225 Round Robin Scheduling Conder the folowing example for car idea of how processes wil be queved in ound robin scheduling Procese [Aral Time | Burt Time 3 © rt the quantum time be 4 ut The order in which processes wil be executed depending on tis quantum times shown in figure 226 below ‘Figure 226 Schacing of Process in Round Rabin Schad arasmucuns gtconpam) ant us {Program for Round Robin Schedulng using Queve ocudecstdan> struct process f euarrane: Incanto intcomolete float te 010; inte let (00% /iqueve Int ent rare: oid enqueue) i rear==109) ‘ pent overtow't rex, eares: rete’ lront==-1 front, Ine sirQseven) intl fortetonthearearke#) qi Wante=d eum: ’ ew: , od sorta) ‘ struct process temp: forgeries) forgeienjenje*) a tonptla0 ‘ tema emer esters: , ’ ’ void mang ‘ (nt tess bao: owe tom aged, printer no of processes: sani" foindenAseniences) ‘ Pihnamene rintnEnter the arial time and but te of process Ncpiinamey, parepnbe rack & QUtuts “para sacrum Comput BI penta the be quantum > sent 80. entyarnatt erqueect,—_Hfenquee heft process ere race encvton rer fortes artes 80 entered c indeaoin. permet) ‘ inter reese vg reicing oe ees tan requ tne gut eee rome complet rer Nene scimtonestiat 9 ecineone stat stint tb fogeQienise)—_(Henqueve te process nine cone we sheng ee samo ‘ equ: , , , ese / more bantime quamaen ‘ treet atin pont Ne sCLname, forgsdjenioe) 1 re oe oat erase te procenes wich ave come scheduing fst Moliatewtme WM pilcomgieed at 88ts/AA Istnaveved=1) t engl: , , ecpeve then enqueve be wore proce: , , pone NareArvainaesTinetWalingTine tT tieondtneeNemalaegT: foriadienies) (wget Pine RCH RANNAUNSIANAE ME ptt beet Re , rng naserage malig meshing: , our: ren of process nter the arate and burst time of process A:03 Enter the al ime and bust time of process 8:26 Enter he ara time and bust time of process C44 Enter near te and burst tine of process 0:65 Enter heal Une and bust time of process 8 2 beet rege poceseeatenorderA# CD BED [asl e [elo ‘Nea wg te CD fevewoanase Mlle Croce Queene 1 soricteg es Aono beau (o Nom etoeve (0) Mts completely independent ta ype (© Mis colecton of dierent data types () tmlamertation Detais se ndden An.) BATASTRUCTURES Stomp) ga rac ques, 22 User push {lament nthe stack having aed five ‘ements and having sack sine at 5S then stack becomes —_ (a) Undertow 0) Overtow (0 Cas {) User Flom in. 3 In the stack. user ty to remove element fom the cempy stack ten teed as (a) Garbage Cotecton (0) Undertow of Stack (e) Empryeotecton (3) Overfow of soc (ana. 29 4 Proceso removing element rom the sack scaled (a) Pop (©) Delete (0 Push (@) Remove (Ana (a) 5S. Im te sack process of Inserting an element inthe ‘ack caled at (a) Pop Push (@) Brauaten (@ Gene ams on) 6 Stockings severe (Fro None o hese f@ wo (@ UFO meta 7 Instack,Inseon nd deleton canbe done ony atthe elem @ ay © Top © oy (None of he above (ans. 0) 8 Which ofthe following statements) about stack uta structure ware NOT erect? (a) Stace dit srucure can be implemented wing linked it. (0) New node can only be added atthe tap ofthe stack (Stack isthe FO data structure (G) The last node at the Bottom of the stock has 8 NULL (ans (2) 9. linear isto elements in which deletion can be done from one end ont and meron can take place ony atthe other end (aris nown asa? (2) Queve ) Stack (@ Tre (Unies ist (Ame) 10. Aqueve a? (a) FFO etn Fist Out st (0) UFO astm fst Ov st. (0 Ordered aay nea (ama 11 data srvctre in which elements canbe inset or Geited autrom both the ends But natn the mdse (a) Queve (9) Gren queve (6) Dequeve (6) Prony queve ns. (€) 12. normal queue implemented using an aay of 28 MAX SIZE get ful when (a) ReareMax SE 1) Frontarearet) mod MAX SIZE (6) Bromerearet (8) Rearstrone (ans ca) Descriptive Questions 1 what ic Ponty que? Gives implementation Deets 2 whats Queve ADT? Mention ts operations 3. Define Stack Us application of Stack 44 Wote a program in ‘C to implement crclar queue ing aay May 18 _Wrtea program to mplement pron queve Wine & program in © to implement double ended queve Dee-19 7 Wotea shen note on Crear queue 1. SK Srvastna Deepal Smastna Data Suuctres ‘Through C 898 Pubicatons 2nd and Revie Eon, 21 2 Yedidya Langsam Moshe) Augensten, Aaron M Tanenbaum Data Structures Using C8 Ce, PH 1996 kaon 3. Reema Thargx_ Osta Soucures Usng C Oxford Unwesy Press 2nd ton, 2014 4 SRO Group: Oana Swuctures using C TMM, 2nd Eton Po 5. Mesh Gupta Data Suuctre Using °C, Iterations! Book Houle Pt Ut. et Eton 2012, tpn np cin Iepsv/opendatstructrs org eps) coursera.org 9 nept/wwovatpincom/dat-structure tutor 10. naps, gateviyaaycomydatastretures/ 1. ep sanfounday com Aan Chapter 3 LINKED LISTS © evotucton Reprertion ot ned and ear Unie is ‘Seo Stade Sey ake 213 redscion to Uke Ut 32 bepresertaton Und Us 23 Unie tvs Arey 1A Types inked Ut Sg keds, Doubly Uke Lis and Cra Linked Usts 35 Ustad Un nplemertaion of Stack 216 Une Ui plementation of Qe 27 popbeasens cl ned is Peewee saeerce, (Sate the ndvantages of Und at over ray, Mays8 + Titon we hae see ear ta novus Ie ay, stad and queues nal these da sevcres, elements se sored in contigs memory locations. cass of the fied sie fay, whe sg aay or stad /queve lrpereration vig ary, weave noticed that we arnot 284 eeants mare tan these ofthe ay. Silty in order wo aod he Lea cot of zon and dele, we need to ens that he eee in heat re net ed contguouty, + Unk te is the data strscure which i nt bounded (o ob ese resticions, Cements in the led et can be mored in noncontiguous merry locaton. Since sie ia ct ied, we an 244 element ayia and anpuere in te it. The ony restion wth the inked iis hati oes not ow endom acces elements te rays. The elements in the ed fat can be scesvedin wequenta manne nly. a sapiivscon, ee i edna ramen epreertation sd Addon. A linked tat is 0 liner collection of dta elements cae Node very node it compied of to pons: Data and Pointer to the ned rode, Let pat of the node stores the Data and Right part contains the adress ofthe nest node Hence we can vaverse through the list sequential. Uniad Het can be used to implement other data suucues ike Suckand Queve 10 }- Dau Pointer Fur 3.3 Anode ving 1a dts nd ple Tree an be ent oF more dis pans in the nate. Aepeing one ppcton Coad aa] Fier 32 And us +The Une itso In sore i 32 con 5 odes wht the dat elements 10,2030, 40 and 50. ‘As we can te Inthe Fig. 126, every Und lit hos 8 a ATA STUCTURES 6 Compute on Luna uss pole Sta a indeste rat of te at which aye Stores the address of te fet node, Tough Stan we Can stan vovering tented Et sequel, The at node of the inked let dors nt contain any poner 10 in contin Nl inthe pier econ. Mil is ected by and Wis denotes the nd of te fet When Start = uh tines the inked te empty, + We can implement» Inked It wing the folowing codein sant node ‘ inn day, struct node est x ‘A ined fet can be reprezeted fn ro ways: Sc od Pyraic ‘Stacey representation + In Suse reresernion tw Eoked fat will be ruining to parael aso same Sz. The festa, if wil recta and he cher aay, Unk wit tore the adden ren pote, [ar] wo ue 10 20 0 Ey Nu 30 z ‘Figure 3.3 Stave representation of s Unked Uist + Above figure shows 2 ste representation of the linked fst shown In figure 32. Here. Sat = 2.50 Inf = 10 which the fest element. ‘+ To.get the nent element Link pa with the same index Is checked Le. Uni2) Unk(2) » 3 indicates net ‘elements socatin 3 olefin] « 20 and Unk) 1d 39.00 4 Atthe end we get Unk6]» NULL which ndates end ofthe Hoked ist So, we gets quence: 1020 3040 50. Dynamic presentation: in dame represerazion 2 loked fat shown nthe fem of nates a hownin gue 32. + Geerrnode condi of two parts Dota ard Ne + Aa shown i figure 32, the ft nade contains 10 9 aa pan and fs Mert part cortans addres f the rer nade. Modes ae converted 9 ach ther Brows the rem pote +The Mert can of the last node contins NULL to Inca en of tre Ente Et + 50, saring from pointer Stan. we get the Ket of ements #2102030 40 5, Gz umepusrvsanmay id) Difference benween array und Finked Ese army inked st ‘ray eerares we sored | Barents of Unked Fat in contiguous memory | may or may not be sored locations random menery locations ‘ray elements canbe | Bement ofthe inked ist ecessed dom, en be aed in sequential manner, sartng from Headsstt See tte aray i taedio| Memory alocten & sate memory alocrtion i | éramic becawe se is one. net now previously Wecanetadd demensin | We can add elements an amay once the size is|anpime as size it not fed. ard, ery stores elewerts | Unked ist wares he elements in nodes (4_TYPES OF LINKED UST + Shalyintad lists: can be wavered in forward rection ony, + Doubly linked leis can be vavered in beth the recon, forward aswel backward. + Grculr ined ts: Last node points to the fst node a5 next node and fist nede points back to the las ode as the previous node. Ls = eS ato each ova, we wil i itis PL to (943 Singh Urked it (0 wit» program fr following operations on Hh ‘eked Set) Insertion 2) Deletion 3Troversa. Many ett |e bs tow in Fig. 32, sgl Kee Et | segue of odes containing data wd port to Oe nest node, herce aveing in only forward Grecton i posse. Troe snpestor toe rte 244 Teverig» Unie tit_— Po Ata tt ors tas be oder tO io pong ene doe eked Ut wh Seapets ced t9 Min tee ne pet cl be at re we wh 2 eis bet we end one er pe PC Cronsponte be onwarate Weel natn Po Oe nts Sat 2 rts tele of tke it We il move (peed org eth de a apy procs te Sree poe by Pr ech strode ‘poeta aed cute mabe fren pees toe sees 2 taper eps} and ne Pt sop recente Dt seyret Not spa gto cont ne totes laa Ter cart=0 Boers heen Sead Ai Pe {eseTCose = Comt +1 Ssetre= he het 6. wine Covet emt 34.12 Searching fora Value Ina Linked ust = Searching 2 vale in» Inked Et lines fing wheter gien val present nthe daa par of the ‘node oF not H the abe ie preert. the algethn reise acess ofthe node cotaing the value. nee usr Meer ar We ten Compare Oe Pree recy cts part wie ve beng saris Serr ana. he sexes sucesl and ade (Pat node etaed sing» pe Pos Hf ma tot a, then Pos is 9 0 Nl inde recessed pales Fa 31. we hae been poe ih Wie feta ate t be searched 49, then te sen td son with tw fet nde and vale inex “avers pa wibe compared. Ft Vale we ge {0.20 move to be nest rode, We Qe 3 mate « fourth poe Hence, Be Seach is ices and store adres fis ode row. to search vale Inthe ike Pusan 2 pepe Sips and ie P= Hl vals Pu-> Dua setP05 «Pe Geto stp § ase sere Pu Next sero = ta som Reversing singly Bnked fist + We can revere a singly Ud lst by reversing the pointers in the nest part of every node and then ‘spay the da prt of every node from Start We can revere the pointes by taking two eta pointes, pu belore and patter. P.beforeis used to point 0 previous node and pater pont tothe next node GllteonginalUnked Ets 1-> 2-> 3-2 4-> 5, Revere Linked it willbe§-> 4-> 3-2-9 1 SET ponent = pr before SET prbeore = pty SET pu = pusher 2: pater te Nt SET pirates praher>next 4: tu pe before DATA STRUCTURES (5 Compre) on seca sts SET Pe = San G Regent eps 7 ad 8 while Pte Hl 7: Pem Pt» Oita BSE Pus Pu Hen oon 3.4.1.3 Inserting 2 New Node Inthe Linked Uist + Foradéing x new nade in inked et we need to Cee 2 new nade wing malloc fanion We wil be picking up the space fom the poo! cf free memory hep in sriable. The ten node wil be cated once the memory is aaable, but thre coud be 2 ssston when there no space aalabe inthe poo cf free Imerary, sich + susion would be refered as (Oveion. Overton wil ect when Arable « Nain sch cse we wil pit the message ‘Overton. For insertion of 8 new rode in the Ene fat, we nee 20 consider these four cases: 1. senting anode at the besoing 2 Insering a node atthe end 3. senting anode aera ghen node 4. tnsering ane before a given node. Case 1: sting a nade at the being fefer to the Figure 32. We have 2 Inked Est with $ clement. How, Suppose we wish to add anew node with ‘he data 5 to Os it and tis new node shouldbe te fest ‘ode ofthe Fist. Fooming steps would be flowed: A. Grate anew node by allocating memory. 8 Asin value 5 to the Data part of newt crested ode CMake the Next par of the new node to contain address of the Stat. as Sta points tthe fist, rode. ©. Final, make Stat point to the new created ode, Figure 3.4 Step A and Step 8 Giallo) : Figure 2.5 Step GLAD aba Figure 3.6 step D Aigorttbme I paiabia = Wie ORO Gowsieg? ZSETNDW JODE « Aiatle 557 bralable = salable > Vert ‘& SETNEH JIODE > Deca = Val |S SETNEN NODE > Nest = Sat SET Stan = NEW NOE nom ase 2: ering 2 rade at te end + Rater to the Fgure 22 We have 2 iked fet with § lemerta Mow, soppoue we wich to add 9 new nade wth the data 6 to ths Kt and tis new nde should be te lar nade of the Et We need to te a pointer Peto reach to the lst node. Last node is he one whose Nex paris Mul Sa, staring rom fst node we eovene rough the Unked ist unt we get the lst rode. Once we get the lst node, i's Nec pan cn then point to the newly ered node. Foionng ste woul be fotowed A. Crate anew node by aloczing mamoy. Assign value 60 to the Data part of nenly crested rode. CMake the Ner pat of the new node to Null as it would be the lat node. 1. Takea pointer Pe and inize it to Start Traverse the linked ft untl we get Nest par of ‘he exrentnede as lt Once we reach to the lst node, make ts Nex part two poi to newy crested node la Figure 3.7 Step A Band C sony Uo o-oo) Figure 3.8 step Figure39 sup E DATA STRUCTURES 5 Comput Figure 3.10 Step F ‘gore THIF aioe = Nal Wite OvEAROW Got step 10 2: SETNEW_NODE « Antabe 5: SET Avaiable = Avlabe > Next 4 SETNEW.NODE-> Oat = V3) 5: SETNEW,NODE-> Nes = Null Sete sunt ‘Rept Step B wile Pr-> Next = NULL a:setPe= Pu-> Next -SETPa-> Next = NEWNODE se.b0r (ase 3: eeing a rade afer agen nde. eter to the Rou 32. We have linked ft wih 5 cements Now suppose we wish to add 2 new node wth the dita 35 (ato this stand tis new node should be inered afer 2 ade containing Data 30 (lubed. We wil take one more pinter variable repr along wit Phere Sa. stating from fist node we wavese Ovough the inked Ist unt we get that rode, Pret wl traverse along wih Pir and once we exch tothe nde having Data 30 ater which we need to ser the newy created ode, Prep wil be pointing to tat node and Pu wil be assigned the dies contained inthe Next pat contained in hat ‘ode. Pret wil point to the ede jst before Pi Moke Nest prt of Pepe to polo to new crested rode And then Net pant ofthe new created rode vs point where ts pointing. Following sep would bellowed ‘A. Geste anew node by aloting memon. 1. Astin vale 35 1 the Data par of rely created ode, Toke to polar vaiaies rand Prep and Inia themto Start 1. Traverse the inked Ist unl we get Net pa of the eurent node a 30 LUNE sys each tothe node, Prep Wil point yo erat rss ins Nest os ‘hat ede and assign the ade ‘oP Make Nex part of Prt point 0 newly tes rode. Next 4: SET NEW,NODE > Dats Val unto usts [DATA STRUCTURES St Compute) oo SSETPU= Stat SET Prep = Stat Repeat Steps Band 9 wile Preptr-> Osta le Number ‘SET rept = Pe S:SETPU® Preptr-> Next 10 SET Preptr-> Next = NEW, NODE. 11: NEW,NODE-» Next = Ptr separ Cae: Inserting anode betorea given node 1 Refer to the figue 32. We hove 2 inked st with 5 ements. Now, suppose we wih to add a new node with the data 35 (Vato this Ist and this new node shoul be inserted before a node containing Data 40 (umber. The cate here sina to the ease 3, but in ‘Case 3 we had interest n geting the node ater which ‘we have to insert newly created node whereas here we are interested In geting the node before which we ‘want to add 2 ney created node, Here too, we will ‘ake two pointer variables Prepir and Pt The ‘igetthm wil goin similar manner as previous case. The nly liference i Per wil pont tthe node before hich new node has to be inserted, Pept as usual ins tothe prevous node pointed by Pu. Following steps woul be flowed: ‘A. Create new node by allocating memo. 18, Aston vale 35 tothe ata part of newly created rode. © Toke two pointer variables Per and Prep and az themto Start. . Traverse the Inked lst unt we get Next part of the eurent node as 40 Once we reach tothe node, Prept will pont to that node and assign the adres in its Next part tore, Make Next prt of rept to point to newly created rode, G. Make Next pat of newly created nade to point to Pu ‘Figure 3.16 stp A, 8 Prep Pr son Figure 3.17 Step Prep Ptr ‘(eo aoe Figure 3.18 Step DE sa ; = Figure 3.19 Step FG ‘Figure 3.20 Final inked Uist Algorithme ‘VIF Avaliable = Null ‘Write OVERFLOW Goto Step 12 2:SET NEW,NODE « Avaable SET Available = Avaable-> Next ‘SET NEW.NODE > Data = Val SSET P= Sun ESET Preptr= Ptr 7 Repeat Steps 8 and 9 while Ptr-> Data = Number SET Preptr= Ptr S:SET Pars Par-> Next 10 SETPrepr-> Next = NEW.NODE. TM NEW.NODE > Next «Ptr on UnkedUst implementation of Stack, Deleting a node from the linked Ist + When we ty to delete 2 node from the inked list we must check whether the linked ists empty or not. The une usr DATA STRUCTURES (SE Computer an. DATA STRUCTURES (SE Computer), om Se ato wo ees ater te se incon ton tne an aaa sn a | STS Maa nenoy wnat mare | CS aang et ade aa Figure 3.27 Final inked at the poo! etre memory mared by Aasale pm. | Reese Fig, 3.2, if we wat 0 delete the ast node SET Pu» Stat anon toni teem seem tte ison Le Trsertnctouar mena || tonsa aa ceeryor ising rode nt Ine i we ed | 4 Wereed totale 2 ponte Pte reach 0 he stad, 4: SE Preptr = Per ‘wre UNOERFLOW a wmrmaeereer rere [Sammon wonton prea ar eet | ernest ta ener sores 2. Deieng teas ode 3 elrng ana ater 2 ven nde ase: Deleong te fest nast oat nose # ays ached trough te Stat ple. Irene fdertng 2 node we says check Underion (oravon Whe inked at s nt emety, we can se the De to Sar et Sar pont to te net rode stat sand rode becomes e fst node and tus the ecnse isis gong te the last node mow. This can be adieved though pater Pret. Prestr vay: poms to the previous node of Pu. $0, staring trom at node we waverse tough the Unk Ist unl we (et the last node. Once we get the last node and fecond lst rode we set the Net part of second last rode to Null The following steps would be flowed 1A. Check for Undertow conton. 1h the Unked it & net empty, Take & pointer Py eect (Cane 3 Deleting node aera gen node + Referting to the gue 32 we wish to delete 2 node aher a rode whose Data Is S0Number, we wil take fone more pointer variable Prept along with Pu here. So, saring fom fint node we tavere tough the Inked lst unt we get that node. Pret wil wavese ‘along with Pr and once we each tthe node Rving “4 Repeat ape Sand 6 unl Prep -> Dat = Number S| SeTPrepy «Par 6 SET Pun Poon Nest SET Temp = Pe SET Prgtr-> Nest» Pu -> Nest 9 FREL Teme sooo a ee a liceerg incr wey deee be tt node | andiet contain eto Start 20 Peo wi pong ta ae | og er Singh nad Seergtemmeaentnmt | nein ET amon | Larecnancmertnm mart | mar enste otowng ep woud be flowed ote Prep points to the node contanng Number and Pr | clude iecooae a nmnsemncraniien | Saenrestememmats | Seceees Tete | erates Seuneraseicpa abe ha and let 8 contain address of Start. ‘part of Prepty Null so that this will be the last node. \ist is shown in Fig. 3.27. struct node Sectors || rancor pecans ee See ee: ace a 1 Sheer eos we ener | See . reese i . (GML «= * Seturomnav'iovorans | Smee - per eeneleieres “a-a — ‘points to one node before the Ptr eas +3 isa = a ei) 1. Once we reach tothe nade continng Number Seog Moe cde equ 3.21 Step B pointed by Pept and succeeding nede pointed by | S0™t Node “ser begistuct node 7: . - Seperrr ad pens s mee ors | Sees? ae orem smn ts S = Pani oetorasimarey pantie ~ at a Mens Sa 7 a ar ee 1 WF Sant = Nel im 4 a ala a -a “Gall ta | se Soros, Figur 3.25 Fnlinked tt her deletion of lst node Figure 3.26 Sep ¢ ‘3 ro Unt ss para srucronss pene wvade deleted atte beginning: © t pret yiouNRED STN pert etc ayene ta sows ee" > fre nae teas > greet) Dasani > meta neers ate ONS pre re nw nce ae Seat meena mn ece ton ngs noe: rant ene aero gv oe Prec cee neato beens: veto Core nse th oot rte a pre rese pee OTA rake torte mene ( wt ran oven hea red PONRED UST CATED beak sane excimer ows fans eset best: pretense send te begering?: sare meaner, re oNen Nee rsened te en) cous St « er peers reir Nace iserad beta # gen owe san «roar esa. ‘neuen Node need ser» pven node cou? ‘san eels Dept, retun. struct nde create Mtr node stat) ‘ neu strat node new nod “tr rin reating 2 Unked Ut printer tend: rier the date sant rum: where) ‘ ew.node = (ret node)malosizotsuct node ew. rode» data ou saree ML) ‘ ne pode > nest» NUL: sta nen pode: , ee ‘ pus sat hls oN) peptone pt snertanen node yen usr _Satasmavcruns et Compete) 898) re node-snete NRL, , Prine the data, sean ren , eum sar ) strct node “play strc ode ta) fi struct node"pt it ane=nuU i Prien Uist mp 1 se fi present whletpesnexteNULL) PinteNA etd, pir= prone Prin pr-ndaa, eum sare struct node "ser, begin node ‘tat int eum, ‘rt node ‘new pode, ‘rintninserong a nede atthe begnng\n Pritt the ta: sant: ew node» rut nadernet Nae ew nade» mare ‘new node-snest = sre stenew node, tur st ‘ret node ser. endistuct nade tat) struct node new node. “ptr peatwiaarting» nde athe endin> entre the data seat NE Boe new pode» (stra node?mallotsieotsinct node nw ndie->data = nm pues leg nr t= MUL) ‘ ss , pe srertenew pose: new noes» MOLL. rem nat srt noe rae bforsuc noe“) oem at stra node ew.node. “pres, “ptr preening a node before a ven aden. penetntr te nose 7: DATA STRUCTURES St prnverhe node: sean Anu: pee tere dt sank to ev ode = ct noetnatosetstut nde enrode dita «at ; pre sut ited) q evr: pr=prnert prov nesonste ten pose onetept seus , 7 sctnode delete begs nod i souctnode pt iteansenuLy i rnd Ut empty: , ee f pr =sat-> net sunt pe, eum sare 1 , an) souctnade delete endured at) i strat node See Msan=NUW) n Pins ned Us empty , se ‘ a TDelete anode at the besining ss ees LINKED uss rept pies p-vrent ’ prept-onent = NUL: 5 retum start tract node delete nodestuct node‘) cl lator struct node pret, “2 itsut=»NUL) i prinf(iinked Uist empty , ee ‘ printer the node tobe deleted seante%t" Boum presen whl(pt->datalenun) ‘ preptept r= prone , prept-sned=pt->nert ) eum sta , ouput rune ust Sect anyone te folowing option: Crete Unkes tit 21Dispay Linked Ust 31 nse 4 new node a the beggining] insert anew node atthe end Slinsr.a new rode before 2 gen anode ‘nse a new ode ater a given node neo usts DATA STRUCTURES (SE Com ax 1) Delete node at the end 4) Delete a given node sajext 1 Creating Unked Uist Enter" t0end Ener he data: 10 mtr the data:20 Enter the data :40 Emtrthe data cnterthe data:-1 LUNKED UST CREATED seeped usTor Selec anyone te following option: ‘Create a inked ist 2) ipl a Unkes Ust 2] nae new node atthe beggining ‘nserta new node at the end Sse 21new node before a given anode 6) Insert. new nade aera gven node ‘Tele anode atthe begining 1 Delete 3 nade athe end 51 Delete a given node 1a) ExT 3 Inserting 2 node at the Besinning Emer the data: "New Node inserted atthe beginning ‘em UnKED UST Sect anyone the folowing option create a Linked Ust 21 Display a Unked ist 3) sera new node atthe begging Alinserta new node at the end Slnsert anew node before a given anode 6 ser anew nde ater gen node TDelete anode a the bearing £8} Delete anode atthe end 5} Delete a given node 19)e0T 2 5 10 20 40 $0 semuNRED UST Select any one the flowing option: 11 Ceate a Linked ust 2) Display inked Uist 3] Inert new node atthe beggining 4} Inserta new node atte end snertanew node before a given a node Inserts new node aera given node 7 Delete anode t the begining 1] Delete anode at the end 5} Deletea given node 10) 69 e ‘Node deleted atthe end vuNKED UST Select ny oe the flowing option: 1) create Linked Uist 21 spay inked Uist 31 Insert anew node atthe Beginning Allnserta new node atthe end Sinerta new node before a given anode 6] nser anew node ater given node 71 Delete anode atthe beginning 8} Deletea node at the end 5) Delete a given node toe 2 5 10 20 40 semunED UST ‘Select any oe the flowing option: erate a Unked ust 21 Display a Unked st 3 sera new node atthe begining Alinsert anew node athe end 5] insert anew node before a givens node wy LUND us, STRUCTURE os a = his waed in Masi lye fr Inking of previ, {sere nce aera given oe TiDewte sade tbe Bepeing {ite ode a te ond ‘s] ele a given node he me wet oe preven oe Fine eu tram eben bt dnctans (Shen ret ard whch res eng tay oadtcen Inca nf 238 pode Day rtd at cone ee pte >on > poner erenate 2 temewnepmnn rode Shwe Ft nose dosnt he ay pees. pon pon ater «feces wt Day Ud iat by tg # oeseate ‘ ‘mated om srctnte : sun gre 3.28 ey nad st + Te ooetons on Dy kd at ese at on Sng Uke it face te eros re seve to peor hero we an Woven oh recon on tee 90 need 1 ety Pack of ross nade hve The ony danse of Dovbly nted i ttt cores mon meno compared {> hr bnew eta sucess ary ed it oct ‘ot aon random ness f 64 Doty ao ne on eepton Apptcatone 1 Dowty edit ued by web browne to est song 1 ose in mage Viewer BY Ng MOR AN Pre, ation 4 iso used 0 represent ferent tates ofa game S. tecan be used in any sytem for navigaton where fn, and back nnigation require 3.43 Clreuar inked Ust Tim crea Bnked lit, nodes point f0 €3¢h other ny ala way Le the last node contains a pointer ot feat node of the bt Tis variation 1 possible win ‘Sigly Inked iat aswel as wit Oovbl inked hts wwe can have Greular Singly inked Ist and Crew Doubly inked Tat. We can traverse the Uist in an, Gdrecion forward as well as backward. The ingrammat representation of Crear linked is shown in Fig, 328, oan Figure 3.29 Creular Unked Ust ‘Apliations: 1. Greular Doubly Linked Liss are used fr implementing vanout advanced dita stvetures. 2. Allthe running applications on PC are kept nacre Inked ist for 05 tom keep ack of it 3. Incase of mutiplyer games, ll the Players are kept in * Great inked Ust and as a player's chance ends, the pointer keeps on mown foonard 4 Gieular Linked Ust can aso be used to create Crear Queue 2. Wire» program for fllowing operations on cult Asked tet Insertion 2) Deletion 3)Traversl, May 19, Dec fncude etdon> ode «sting hy ude etsibn> ince struct node et da, inte | ee strct node head # NULL, struct node Yurent = NULL oct emetv0 retum head == NUL: , inetengto( Intlengeh = Utteeeemoty itvead == NUL ( eum o; , cent «head» hiefcurent = head { engine ‘eurent = curent ner , rear engi: ’ ‘ser ek at es lcaion id insert ky, nt at) Merete ain. struct node “ink = (sruct node") matocissectstrat rodelt: ‘pon st tore fst nose thea = tine , , Weelete tes te struct node *dleefst see recent Fs ink struct node “empl = head nead-snent «= head ( head» NULL rear teptin , mark rest to fit ine as st hed « head» next ream te Slated ke return emetine , edspiay tre ts id printisto ( struct node *ptr = head, pret Lar trom te begineeng vend t= NULL filegpe->nest = pen ane TNS) “pe->key pt» daa) Vnk-ohey © bey, ae ink ata » daa 7 ’ H 6stmen0 ‘ahd rine 1. headset «head ete ‘point tt ld tt node weiteatot lnk>net = head 2

You might also like