0% found this document useful (0 votes)
12 views

Data Structures 3

Notes Of Data Structures For BTECH Engineering

Uploaded by

Sandeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
12 views

Data Structures 3

Notes Of Data Structures For BTECH Engineering

Uploaded by

Sandeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 29
Fo 90 1 unit 3 QUEUE Queue! 5 uss queue is a linea datastueluye in which insevfion takes End and deletion takes place ws fist in first out pe acceyed fixst: (oR) place at one end Called weay at one end called Frontend. It Follo (FIFO) fe, the data stowed fixsk will Queue is An Absbvact data stsuchiwe Some what a queue is open at both us and ueue similay fo Blacks. ‘unlike stacks, is. always "used 4p insext data (eng) is ends» one end fo Svemove data (dequeue); © the othes end is used Follows FIFO: + Basic opesations of 2ueue ‘ Basic opesnrone AA , queue opesations may Cinclude.invelve intahaing- ox defining the queue, obliging it, and.theo completely erosirg ndexstand i-faocn the memdly. Heve we: hall ty bu uUeues — queue the queue . and the basic operations Associated with 4 # Enqueue () - add (stove) dn item to the * Dequeuet ) - wemove (acces) an iter From ‘x peek C ) * isfull C ) ® is empty C ) & peek( ) / | This function helps +o gee the data at the | | front of He opueue + The alga'ithe of peek¢ ) function ww follows: Aigner int peek () 1 aetusn Ceueue [front )); j i) bak fk & past festa af 1213141 5] ‘ | i | pet) 5.2 ; | — tsfull ©) + As we axe using. single drneasion array fo implement queue, we dust cherk, for the YEA pointer 6 xedch ab Maxsiz& 4 debesmine that the queue is full: Implement of 6s-funC) function in ¢: » bool isfull © PPro if (deay-marsize-!) = sehesry tyue ; » else elu false; y Edample, Goueue ={ J isfun(g = False Seeptyt ) H othe value of front Is lems didn Min) or ‘0) it tells that the queue is not itil ‘aed, hence que is cry , , at + he AlqBithen tos isernply ) functien ¥ was Follows— Paap Ss bool isemphy ) ? If (front <0 1) Front S ved) veturn hue) else sehuin False; (0x) bool is emplyt)4 : i€ (Front =.= ¥ea¥) should be taken to enqueue (in velusn tue; else xelusn false; 5 Gar @ueue ={ 3 is empl bruce (# Engyeue Opevaren opesation goueue maintain two data pointers , Front and veav therefore, its opesations ‘ave compawatively difficult to | implement than that of ATACKS- (insest) The Following steps | data into a, queue; Step ai checks! the queue ig full. wy esset | glepa vr. If the qpeue is full, Produce ovexHo! And exist. | skepa'- If the queue ig not full, ineverment year pointer +o point the next empty «step ar add. ‘dato element to the queue the weav is Pointing steps: yelurn SucceAs pace: location, where Enqueue ( ) Im ple mentation oF Ergpewel shy yin The following sheps, areas be talea to enqeuelnay data int a queue - Ink enqueue (int data) d if Cis fund) xetusn 0; (eu) Prine (* ovex Flow"); else | i | Yeay= yeast, Ateue Prear} = data; ce 5 te oan Seed data from thre gpeud is A Procers | two slacks - Acces the data’ whitve front is Pointing ani | xemove the data AaFle¥ Feceys + The Following Ateps ave taken to Pevfown — mses * “checks it ithe cyueue is cemophy PP the queue “is _erophy, Produce Binder sts exres § & tp the ee 'S. nok emply, ace os the data whew Fsont is pointing: | + Increment faont Pointer be poinl to the neg] walobte dato ¢ lement ¥ Relurn succeAs pe el or (3) EDOB Fa) __ ah fay fot __ ee 9 afley (< 7) C8) —~ equa oe D Aueue dequeue int dequeue ) it ‘ iF (is emply ()) elurn. 0; else ink data = queue Faont J; front='feont+1; vetuxo data; 4 pepesentain of of Goueue using gray ¥ A queue data shuchue can be implemented using one dimensional ary: ¥ The queue implemented using Seay Alores ool fined ‘wumbes of datavalues * he “mplementation OF qpeue date stack ii ‘aroy is very simple Just define 4 one dimensional array of Specific bie and insert ov. delete the Valug into that aay, by using “FIFO principle with the help. ef variably front! ‘And ' yeas’. | steps The implement main method by ea queue data shuchve using anay we implement aclual operations First Folin, to cveate a emphy queue: ch ave used io the Penn, pecific value. can be inoplementy as follows. Before the below steps steps aelude all header files whi and define a congtank'siZE' with 3 skepa: Declave all the usey defined functions which are used in queue ie Jementation: 4 ? imensional arvay with abow Smz skeps | cxeate a one di (int queue {sv2E]) es variables -\ (ok faeok =! apd sear!) displaying, menu of Step4 = Define two inkeg fyont! and "yea?" and inthalige both wrth” operations list and male ‘guitable fonction calls b we usex 07 Queue. Peeform operation selected by th step + check whether queve is FULL (reaxe maxsizé-!) Stepa = \f it is full, then display *gueue is) Fure!!) Tosertion ig not possible!!!" and texminale the famekion steps + If it is not full then Incvement ‘yéay Valle’ by o”° (wearé+) and Set queve fveay)’=value. stepi;\ check thether quéue ‘is EMPTY (fronts = ¥ea%) stepa: IF i ts empty then displays" @ueue' ie: Empty tt Det fs nol possible tt!" dad» tesminate’ the function: Hgkep3'' iF if ts nok empty ther inexeenent the front value by one (front ++) ‘Then display queue Cfoont] as deleted elewert “Then check whether beth front and veay ave equal (Front == WAN); iF IE TRUE) then get both front ard ve ar Fo NAV" (front =vear--1) ; ispla pisplad check whether queue is EMpTy (front== year) step 4 ¢ sepa i Wie is EMpTy. then display “eueue ig Empty, ‘ard tevminate “he function: steps RE not Empty , then define an integes vaviabl 1 ad Aefront+1} grsege POPES a include < stdiovh> a include ap define SIZE void enquevé Cink). oy void dequeue’ 17: void display ¢ + int queue [SIZE] ,Foont=-ly year=-l5 void enquelint value) it (weave size) printf (" aueue is Fu 1N')2 else ig CfaonEze Wo oe | Faont=0 yeart+) ; queue fea }=Value; printf ("\o Inseation succes!) s yeti void dequeue C ) ; t > it Cfaont = = vee) printf (*\o qoueue 'S empty nl); ele. = d cae ase printf (o\o deleted): tat queue (Front) fyont+ +) , Sfasigis te aoe LAE acon if (front © = ea) ’ front © year -1y 4 s Void displayC ) ? it (yveaye = -!) printf (*\n queue is Emphy")’ else t WES I Printf (“\n Queue elements ave +\n"); for(i e front ies veay) H+) Printf (* yd", queue lit); y : 5 Void main( 9 ' 1 ' tok value, choice; clrstscr} while (>; t Print? (*\n 2*# men #¥#¥\O")S 9 Puntf - (* push \m 2. Pop.\n :3? display \n 4-exil’), Printf ("entey Your choice:”)3 : “scaok (ryd", ¥choide); » switch Cohoiee)s 2 OOH of ES Mens) 2 : coyel. printf (* enter value to be push"), Scant O vd 1, & value); ' Enqueue (value); bveak; Cosea » dequerne C); byeak ; Com 3, display ¢ yy break: defaull printf C*\n Wrong felectiont1!"): 4 y y of * ZF yee MENU #F® push a POP 3 display grexit enter your choice: | enles the value ' be lasest +3 Het MENU #¥* p push 3*POP 3: display enter yout choice) geexik enters the value bo be ingests 4 pax MeNUREF pop. aidisplhy 4. exit t+ push 2° un choicetl, » bn be ingext* 6, push arpep 3) 5 entes yout choices2, enter the value fo be delete: 3 pee MENU #RA Lb posh a Pop 3. des play genie , Epler your choice,3 ea 4 » Ulvs lements' ‘dre 4 iG I aie Inplmendaon of gurus using bo Sack athe probleen of opposite oF this posk we Ave given a.) dato sbucbuve with push and pop opevahors - The laak is j implement a queue using instances of Atack data secs, And opexation on them: A queue can be implemented using two Btacks. bet queue to be implemented be *q and gtacks used ® implement ay te Be StaCKY and shack 2. cap ibe ienplernertes in two ways tu ¥ by making enqueue operation el making Dequeve opesation. Method-! + : 7 —_—~ By making engue opesation cosHy This method makes gure that bldgt entered clement is always at the top of’ stack) + So thak deqptut, operation qust pops From’ stack) * To put the Element AL bop of stack), Stack @ is used. F sbile slacks is net emphy push everything from stack) ard to stack2. « push Xb stack! (assuming size of stacks is Unlimited) y push eventhing back 4 Stack. hese tHme comp levity wil be 0(n) pequeue (a) a # WF stack! empty then evsov % pop an item Fron stack! and velusn ib. pese tine complexity Wil be oct). ¥ Time comople xity ‘ push opevation : on) In the worst Case re hee fate whole ot stack! info stack 2 Pop opesation » ot) same as pop operation in stack’ * dusiliay space: O(N) -use of stack for stosing values. ar method! Enque ues = Stack _ sf CT __ Step : simple! Method | Dequant oy ; shops | mn = pce SMP ; ) , } | t ’ iB} ny | | | tt |" } Ye ‘ 1 | 4 4 | | 2 | quell | lt | a tees stacy? | Hh Teta Vilas Step- ‘ t fash: le ea \ ( ' | To 5 5 r | [bse tact he My staciel w SE@ CK RO! bey, SARC DS. | lia 3 ‘| Method @ , \ By making dequeue opevation testy In this method, in enqueut apevetion, ‘the new element is entered at the top of tre Atackel «In dequeue operation, 'f stacka is empty then al) he elements are’ rnoved te stacka and Finally top of stack & is xgetinned- Enayuave Cox) ir » push x b stack! (assuming si Here time complexity will be ol) sige i stacks is unlinle] Dequeue (%) | "If both stacks ave em ply then a error a+ IP shack is emply while stack? is not empty + push everthing trom stack) to stacka. m stack and ageturned tb. Heve time complenity will be 0(9), 3. por the element Fro Complex ry Analysis ‘ K Time complexity push opera Hon * on Same as PoP opesation in tack pop operation: in the Worst Cow We have: empty hele of aback! inky Sstacka 4 duxikary space: O(N) use of stack for stosing values. 4 include zstdio h> 4 define man 5 void pusht (int); yt Popt (void), void pusha (int); e int popa (Void); void display (void), ink fopl=-t, fopae-l) 5 void push (inkX) 11 fax], Salma], 1 sth (+4 topl= J ink pop ) } : if (bop 22-0) printf (“ undewflow); else _ Zebu ( sti topi--]); 5 Void Pusha Cintx) t Sta[++ bopa]= | int popal ) ui ! if (topaz = -!) Paintf (underffow") } else | Y aed Corattopa-LI)ps ons rte ao 5 ; —_ Enqueue (int x) 1 wy | if (topr= = may-!) | Prinkt (" Queue is overPlow")/ \ else while (top 12-1) pusha (popi))/_ ae Fa yy Push) (4); hse while (topa 42-1) lei r bia Pusho (PoRA_D)S Be \ os \ int dequeue C) t Baie ideuy h if (topi<= -1) Printf (" goueue is undewfovo") ; else ; ' *PrintF (* popped element is, f d”, poptc))} y void display (void) 1 if (topi= =-1) Printt (* @outewe is Empby"); else t Ee pin lf (* gouetie now ||| \n"); oN for Cat Fe gopt ise ost ) printf (* xd", sHEi1)! lat main ) ink chy % * us \E 2edisplay"); print F("\o I enqueue \t a.dequi seat (“xd", &eh); switch(ch) ) ‘ cose 4: printf (* enter ao element) 5 seanf ("yd", 8%), enqueus ,; | bseaky cose ds, dequeut () beeak; | * coge’s t display ¢ 1) byeak} cosed + Exit Loy} 5 } while Ccht = 4); xe turn o; 5 j Is Enqueve — &: Dequeut 3.display ' | eotes an element Ls enqueue — ADequent > clisplay ! | enter an element 3 iF Enqjueut a. Dequert display 1 Enter da element $ 2 3 Le gnqueue — ardequeut 3. display | @ueue now!!! + 93 replay, & hh Enqueue 2 clequewt vn -display 3 I gnquet 2 deque * Pia queue now!!! as . bk enqueue a Dequeue 3. display n i entew an element # ‘i 3.dis play 3" Ie enqueue a'Dequese goueut NOW 434 Applications oF @teue 4: elyoulae queve Civeulay queue is a inedy data shwuchuve in Which the opexations ave Performe d boyd on FIFO. psinciple card the last position is connected back fo the first position tb make 4 civele. Ik Is also called "wing buffer" prone ; x o > wer t In 2 nevmal queue, We Gan insest elements until queue becomes full, Buk once queue becomes full, We (A Not insert the next element even if teve is a space infsont of queue: - clrculay- asert circular doueut ( Coseut, REA, Front ,1/Ihern) Hove, Cauene is A civeulay queue there tp stove data. pea aka. Rear aapeseots the location in which the data element i's ty be insested and Front vepresents the location from which the data element is te temoved. Heve N is masimum $13 of ceoucue and finaly, Hem is the new ikem tp be added. Inibially Reaveo and Front =o Aer 1 if Front 0 and Ret=0 then sel Frook=1 aed ge ty step4. a. if Front =1 and Reav=n ov Front = Reda+! then prink :" civeulgs queue overflow" and Rehern 3 (F Reav=N then set Reas= 1 and go fo step 5 4. Set Reav= Reav+! + Set Ceoueue {Redy] = tern BY consides the following civcular queue with N=5- asinsest lo, Reay=t, Frontot io a in Initially Reay=0) Front=0 \o ' a 3 3» Insext 50, Rear 2, Fiont-1 4+ Insext 80) Redv=3, Front=o pork : \ Rear —- eet 2 - 0 y 2 4 7 4 20 5. Insexk 4p 5 L ee ome Re aes, Frode! & dadete Front, peared Foot & 1 . (| e Vp nok Addy) | 6) 3 .~ - \4 ) ste Jnsovt loo, Reave 5 prontea Ge Insert 40) Reav=! Front. v ' Reayy [3 8 lo ( 4: Insert 140) Reavz1,Frontea 10 Delete Front, Rear=1, Fy), AS Fronk=' pear+l, So Queue Reay ; over flow - Ne Delete Frodk, Reaye!, Prent= 4 1 peay Fox pelete operation ne Rear, Item) Delete - civeutay-@ueut (Ceoueut, Front, Peete See « where data stored» Reav reepreents clement is bo be insevled and-fr here cwueue is the plac ane location in, which dato ata element to be represents the location From which te d rn, Initially Frow=1 vempved: Front Element is assigned to ike Al gBitin 1+ 1f Fronk=o0 then | paint i " Civeulay @ueue under flor” and Rehern _ i MU fro pelete ier | a Sek ikem = Ceoueue {Front} 3+ IF Front = N Fen set Front=! and Rebun | Front = Ready th all Re en set Fronteo ae Front And x. we set 2 Front +1 sche Return ‘a Je Proqvor esarol Pay tf include < stdio-h> #f include dt define max S void push Cink); ink pop (void); void display (void); ink que(max], v= -!, fe-l, Leo; void push (intx) t if (22 maa) printf (" @ueue is ovesftow"); else 1 “xd atl) mar; quels] =X, Ltt, J ; 5 . iné pop (void) 2 if (t= = 0) Printf (" @ueue is undes Hon"); else l Fe(Fey.mary ‘ Printf (° popped item is id", quel fy); Je} ; 4 Vold display (void) 1 if (dee 0) Print ( muewe is Ernply"), else ? ink t) Printh ( @ueue now! t No"), le fal for (ink dels jee R3d44) ! MH Pink (" fd", quécin); | Te41) ymay; 5 \ 5 ink maint ) t int ch,x; iL! do} 4 > fs printf (*\n tpush IE + POP\E 3-display"), geant (* 7d", &cb); Switch (ch) 1 | Coser +. printf (" entey an element”); scant (* xd", YX); push (x) 5 ‘byeak; Cose a pope), break; cose 3 displayt ) + beak; Coed exttlo) } 5 while ceh! = 4); yetuan 0; | 3 + push 2: PoP 3-display | enkex an Element 6 » push a pop adisplay 1 entes an element g ly push 3:pop adisplay | entes an Element 4 |p push 3: PoP 3-display a | pepred ikem is 6 | js push a PoP 3 display 1) | enter an ¢lement | 14 push 2° PoP 3-display 3 | queue now! ! ! $4) pPaement | | Dequeue ov Double Ended queue is a type of queue in which insestion and yemoval of elements can be pevformed from. either From the fetal: ov voay TUS; it does not follow FIFO sule (givst im First Out) | tron From ae foe AG-EEEE | 1 \ngetbion aE t : toe fot layeation at Reay i dhe ved f Types of Dequeue _represertation . Types of dequeue * toput Resteicked Begue In this deque input is yeshicted at a single | but allows deletion at both the ends: * output Reshricked Request In this Dequeue, output is vesbricked ak a single a but allows insestion at both the ends. opesations 00 A Deque In the civeulay array implementation of deque- In circular avvay , iF the array is full, we start From be * But in haeay aria implementation, If the array is fy no more elements Can be inserted: In each of the operations below, if the avvay is fully” Overflow meta iS disown: * Before performing the following operations these Steps ave followed. |) Take an avity Cdeque) of size n 3+ Sek bdo Pointers at the first position and set feont=-! Ready = -} ~ Insert ak the front = Insest at the Reavy 2 3: Delete From the front 4. Delete from the Rear. yiosert at the Fae EE | | gpis operation Adds An Element at the front | push gront (x) oy Hf te2-1) then gy printf ("Not possible to Add from front") 3 else al gs. De@tflex; 6 Fe FRL 4 g- Insert at the Ready | ee A this opevalion adds an clement at the Front: push Reas a) 1 it (¥e2 Mas-l) then printf (" Nok possible fb Add -Froro Reds"), 3. else ‘ a2 5: D@lr+xj=% ey 3 Delete al at he Front This operation delete ao element froin the Front pop Front (x) “AF (fe =-1) then 3, Print ("Not possible f delete from front") 3 else 4 1 5+ xelura(daolee +) ; 4 Delete at the Ready This aperaon delete ar element From the Fronk. pop Reav(x) i be | (vee -2) then ; “ | a prinkF C* Nok possible ty delete From Re \ 3. else 42 s welurn (Dm tv--1) 5 bo fave Progam includ eateis:h5 at include £ stdlib-hy tt define mare void push (int), ink pop (void) Void display (void); ink Dque fonda xe = “4 Void pushR (inkx) TF (se=max-l) , Print? (" vot possible fo add “From year"); ] else . Dave lwtrdex, ; fo | votd pushe Cint x) i ip CRE 2-1) printf (* Net possible te add from Pronk"); else | Dquelf--Jex; void PopR (wid) ? if (fez¥) printf (“@ueue is undes flow"); else printf ("popped item is yd", Dave {x--}); void popF (void) d i¢ (Fe=7) printf ("eoueue is underHow"), else printf ("popped item 1s y.d", Dque (++FD); j Void display(void) ip (f-=¥) printf (“@ueue 's emphy"); else 1 int f; printf (" @ueue now !LL\n"): for (int i= Fels igeyy it) printf (“xd Dauelil); int main( ) q int ch,X> do} print (* aareva\n b push \E 2 & pop E\E s:display \o")) seant (* zd", Bech); switch(ch) 1 pushF \r 3-popR\E printf (" enter an clement)? : OG casel! scanf (* yd", BX); pushR(x), break; an cement") coue at printf (“enter ScanFk (“y¥d", Yyr)s pu she (x); break! case3: poprt)s break; cosed, POpFC)} break; © cose Sh % display¢ 2) _> break; cose 6. Ext (o) >; \ } while (cht = 6)) weturn 0; 5 ole = lepushe 2 push 3-PopR- 4+ PopF svdisplay } entey an element 4 ’ fr PoshR &: push ’%3+ pop’ 4: POPFI 5 display 1 enter an Element 6 }: PushR a PUshF 3:PopR 4 POPF 5-display! enter an element 3 inti 1) pushR @+PushF 3:PopR 4: POPF sdisplay + popped element is 4 PushR a@'pushF 3: PopR pope sr display 2 enter an Element Co) pushR 9. pushF 3:popR 4:POpF S display 5 @ueue now!!! 9G 6 ¢ priositg Vueus A priority que sa Apecial tyre of queue th wlhich seach element amocialed wlith a Priorihy And ls Avwod 4 fo Ibs puidlity: IF the elernents with Hoe Aame Peithy aceddin occur they Ave served aceBiding to theiv order in the queue: cqeneraly «the Value of the element itself is considered fot assigning the PrtBity For example, the clement with highest value (5 considered as the highest pxidi clement. However, in other cd ses, We qr PI can assume the element with the lowest va lue as the fishes Prigiity clement. In othes cases we C49 het prigibies aceBiding fo our needs. a poert vile ae idity— ape BO emp a Lue Ino quene the fissk-In - first -Ouk cvule is imp! the Values ave removed hy is vemoved lemented phereds , ina pridity queue onthe basis of pridiity* The element with highest pridh Sivsk- lrplementation oF RUDI Queue . pridity queue Can be implemented usin Sse heap data struchie ov a binary Aearch tree » “Heap data ghucheres’ Provides an Efficient implementation q an array, 4 linked of pridity queues + Amare heap is implement in the ‘following opeya|. = insert - qt trichest Priovity() = delete highest PriovityC ) A compasative Boalyss of direst implementa, of. pribtty queue is_ given below: pata shucluve | iasere Jelete Linked: list 00) _ olr) | gested Linked list ofa) 00) | Sorted dAvray tA) be oti) | unstited Avvay 0 ant _olr) Binary near; oltegn? | _ oC team) PuiBity queue operations Basic opesations of a pristty qpeue are inserting, Yemoving and peeking elements: 1+ Ingextin an element from the peibdily queue Inserting an element inbo a pridtly qpucue (max-heap) ts done by the ollewing steps. | Insest the new element at’ the end of the trees | Ba 4 6 by O ©) Insevt an element ab te’ ° Heapify the tee end of the qe lement ror he Realy the PuBity queue pelebing ae elerent tron Pity gpevie (en au-he ap) ig dene aS Fellows yy elect the element * Swap it with the fact te be deleted Clement rp (Gq) far i = aa / / OQ @& © 5» 608 8 ye snap With the last kaF node ekment- + Remove the last . HeaPihy the tee element / @ ps B fh Ls bb 6 ea pity the paiihy Pe | Applications Of pridity queue anaer™”™ ” oOo » pigkstro's algpithm ° fot implementing atack + for load balancing Ard interupt haedling in an perating system: * For data comprersion in zeuftman tod | + Machine scheduling eal s Heap Sout

You might also like