Sei sulla pagina 1di 186

Session 1 Advanced Concepts of C and Introduction to data structures (Page 1 22) 1.1. 1.2. 1.3. 1.4. 1.5. 1.".

. 1.%. 1.(. 1.). 1.1+. 1.11. 1.12. Introduction Data Types Arrays Handling Arrays Initiali ing t!e Arrays. #ultidi$ensional Arrays Initiali ation o& T'o Di$ensional Array Pointers Ad*antages and disad*antages o& pointers Declaring and initiali ing pointers Pointer Arit!$etic Array o& pointers

1.13. Passing para$eters to t!e &unctions 1.14. ,elation -et'een Pointers and Arrays 1.15. .cope ,ules and .torage /lasses 1.15.1. Auto$atic 0aria-les 1.15.2. .tatic 0aria-les 1.15.3. 12ternal 0aria-les 1.15.4. ,egister 0aria-le 1.1". Dyna$ic allocation and de3allocation o& $e$ory 1.1".1. 4unction $alloc(si e) 1.1".2. 4unction calloc(n5si e) 1.1".3. 4unction &ree(-loc6) 1.1%. Dangling pointer pro-le$. 1.1(. .tructures 1.1). 1nu$erated /onstants 1.2+. 7nions Session 2 Introduction to Data structures 2.1. Introduction 2.2. Data 8-9ects : Data .tructures 2.3. Pri$iti*e Data structures 2.4. ;on Pri$iti*e Data structures (Page 23 27)

2.5. I$ple$entation o& t!e Data .tructures 2.". A-stract Data type 2.%. Algorit!$ and pseudo code 2.(. /o$ple2ity o& Algorit!$s

Session 3 Arra s 3.1. Introduction 3.2. 1*aluation o& Polyno$ials 3.2.1. Polyno$ial in a single *aria-le 3.2.2. Polyno$ial in T'o *aria-les 3.3. .trings 3.4. .tring 4unctions 3.4.1. .tring <engt! 3.4.1.1. 7sing Arrays 3.4.1.2. 7sing Pointers 3.5. .tring /opy 3.5.1. 7sing Arrays 3.5.2. 7sing Pointers 3.". .tring /o$pare 3.".1. 7sing Arrays 3.%. /oncatenation o& .2 to t!e end o& .1 3.(. T'o Di$ensional Arrays 3.). .parse #atri2 3.1+. #ultiplication o& t!e sparse $atrices 3.11. #ultidi$ensional Arrays

(Page 28 51)

Session ! #in$ed #ists

(Page 52 8"

4.1. Introduction 4.2. .ingly <in6ed <ist =or> 8ne 'ay c!ain 4.2.1. 4unction to add a node at t!e end o& t!e lin6ed list 4.2.2. 4unction to add a node at t!e -eginning o& t!e lin6ed list

4.2.3. 4unction to add a node a&ter t!e speci&ied node 4.2.4. 4unctions &or display and count 4.2.5. 4unction to delete t!e speci&ied node &ro$ t!e list 4.3. Dou-ly <in6ed <ists =or> T'o3'ay c!ain 4.4. Applications o& t!e lin6ed lists 4.5. <in6ed lists and Polyno$ials. Session 5 Stac$s and &ueues 5.1. Introduction 5.2. .tac6s 5.3. I$ple$entation o& .tac6s using Arrays 5.3.1.4unction To Insert an ele$ent into t!e stac6 5.3.2.4unction to delete an ele$ent &ro$ t!e stac6 5.3.3. 4unction to peep an ele$ent &ro$ t!e stac6 5.3.4. 4unction to c!ange an ele$ent in t!e stac6 5.4. I$ple$enting .tac6s using <in6ed <ists 5.4.1. 4unction to c!ec6 '!et!er t!e stac6 is e$pty 5.4.2. 4unction to c!ec6 '!et!er t!e stac6 is &ull 5.4.3. 4unction To pus! an ele$ent into t!e stac6 5.4.4. 4unction To pop an ele$ent &ro$ t!e stac6 5.5. ?ueues 5.". I$ple$enting ?ueues using Arrays 5.".1. 4unction to insert an ele$ent into t!e ?ueue 5.".2. 4unction to delete an ele$ent &ro$ t!e @ueue 5.%. ?ueues using lin6ed lists 5.%.1. 4unction to c!ec6 '!et!er t!e @ueue is e$pty 5.%.2. 4unction to c!ec6 '!et!er t!e @ueue is &ull 5.%.3. 4unction To insert an ele$ent into t!e @ueue 5.%.4. 4unction To delete an ele$ent &ro$ t!e @ueue 5.(. /ircular ?ueue 5.(.1. 4unction to &ind t!e ne2t position in t!e circular @ueue 5.(.2. 4unction to &ind '!et!er t!e circular @ueue is e$pty 5.(.3. 4unction to &ind '!et!er t!e circular @ueue is &ull 5.(.4. 4unction to add an ele$ent to t!e circular @ueue 5.(.5. 4unction to delete an ele$ent to t!e circular @ueue 5.). /ircular ?ueue using lin6ed list= /ircular <ists> 5.).1. 4unction to c!ec6 '!et!er t!e circular list is e$pty 5.).2. 4unction to c!ec6 '!et!er t!e circular list is &ull (Page 81 % 113)

5.).3. 4unction To insert an ele$ent into t!e circular list 5.).4. 4unction To delete an ele$ent &ro$ t!e circular list 5.1+. 1*aluation o& e2pressions 5.11. Post&i2 e2pression 5.12. Pre&i2 e2pression Session ' (rap)s (Page 11! 133)

".1. Introduction ".2. Ad9acency #atri2 and Ad9acency lists ".3. Areadt! &irst searc! and Dept! &irst searc! ".4. 8t!er Tas6s 4or T!e Brap!sC a. To &ind t!e degree o& t!e *erte2 -. To &ind t!e nu$-er o& edges. c. To print a pat! &ro$ one *erte2 to anot!er. d. To print t!e $ultiple pat!s &ro$ one *erte2 to anot!er. e. To &ind t!e nu$-er o& co$ponents in a grap!. &. To &ind t!e critical *ertices and edges.

Session 7 *rees (Part 1)

(Page 13! 181)

%.1. Introduction %.2. ,ooted Tree %.3. Ainary Tree %.4. /reation o& Ainary Tree %.5. Areadt! 4irst .earc! %.". Ainary .earc! Trees %.%. Ainary .earc! Tree /reation %.(. .earc!ing a *alue in a -inary searc! tree %.). Dept! 4irst Tra*ersal o& t!e tree %.1+. Tree Tra*ersals %.1+.1. Preorder tra*ersal o& t!e tree %.1+.2. Postorder tra*ersal o& t!e tree %.1+.3. Inorder Tra*ersal %.11. 4unctions to &ind Predecessor5 .uccessor5 Parent5 Arot!er

%.12. To delete a node &ro$ t!e tree %.13. 12pression trees. Session 8 *rees (PA,* 2) (.1 Introduction (.2. Ainary T!readed Tree (.2.1. Inorder T!reading (.2.1.1. To create a si$ple -inary tree and t!en t!read it (.2.1.2. To t!read t!e tree during creation (.3. Postorder T!reading (.4. Preorder Treading (.5. Tra*ersal o& Ainary T!readed Tree (.5.1C Inorder Tra*ersal (.5.2. Preorder Tra*ersal (.5.3. Postorder Tra*ersal (Page 182 1+')

Session + Searc)ing And Sorting ).1. Introduction ).2. .earc!ing Tec!ni@ues ).2.1. .e@uential .earc! ).2.2. Ainary .earc! ).3 .orting ).3.1. .election .ort ).3.2.Au--le sort ).3.3 #erge .ort ).3.4. ?uic6 .ort(Partition 12c!ange .ort) ).3.5. ,adi2 .ort ). Heap .ort

(Page 1+7 225)

Session 1 Advanced Concepts of C and Introduction to data structures During this session you will learn about: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Structures. Arrays. Pointers. Advantages and disadvantages of a pointer. Usage of pointers. Difference between arrays and pointers. Passing parameters by value, by reference and by address. Dynamic allocation and de allocation of memory. Dynamic arrays. Scope and lifetime of a variable. Unions. !numerations. 1- Introduction T!is c!apter &a$iliari es you 'it! t!e concepts o& arrays5 pointers and dyna$ic $e$ory allocation and de3allocation tec!ni@ues. De -rie&ly discuss a-out types o& data structures and algorit!$s. <et us start t!e discussion 'it! data types. 2- Data * pes As 'e 6no' t!at t!e data5 '!ic! 'ill -e gi*en to us5 s!ould -e stored and again re&erred -ac6. T!ese are done 'it! t!e !elp o& *aria-les. A particular *aria-leEs $e$ory re@uire$ent depends on '!ic! type it -elongs to. T!e di&&erent types in / are integers5 &loat (,eal nu$-ers)5 c!aracters5 dou-le5 long5 s!ort etc. T!ese are t!e a*aila-le -uilt in types. #any a ti$es 'e $ay co$e across $any data $e$-ers o& sa$e type t!at are related. Bi*ing t!e$ di&&erent *aria-le na$es and later re$e$-ering t!e$ is a tedious

process. It 'ould -e easier &or us i& 'e could gi*e a single na$e as a parent na$e to re&er to all t!e identi&iers o& t!e sa$e type. A particular *alue is re&erred using an inde25 '!ic! indicates '!et!er t!e *alue is &irst5 second or tent! in t!at parents na$e. De !a*e decided to use t!e inde2 &or re&erence as t!e *alues occupy successi*e $e$ory locations. De 'ill si$ply re$e$-er one na$e (starting address) and t!en can re&er to any *alue5 using inde2. .uc! a &acility is 6no'n as A,,AF.. 3- Arra s An array can be defined as the collection of the se"uential memory locations, which can be referred to by a single name along with a number, #nown as the inde$, to access a particular field or data. D!en 'e declare an array5 'e 'ill !a*e to assign a type as 'ell as si e. e.g. D!en 'e 'ant to store 1+ integer *alues5 t!en 'e can use t!e &ollo'ing declaration. int A=1+>G Ay t!is declaration 'e are declaring A to -e an array5 '!ic! is supposed to contain in all 1+ integer *alues. D!en t!e allocation is done &or array a t!en in all 1+ locations o& si e 2 -ytes &or eac! integer i.e. 2+ -ytes 'ill -e allocated and t!e starting address is stored in A. D!en 'e say A=+> 'e are re&erring to t!e &irst integer *alue in A. H 33333333333333333 Array3333333333333333H A=+>A=1> A=)> &ig(1). Array representation Hence i& 'e re&er to t!e it! *alue in array 'e s!ould 'rite A=i31>. D!en 'e declare t!e array o& .II1 ele$ents5 '!ere5 .II1 is gi*en -y t!e user5 t!e inde2 *alue c!anges &ro$ + to .II131.

Here it s!ould -e re$e$-ered t!at t!e si e o& t!e array is Jal'ays a constantE and not a *aria-le. T!is is -ecause t!e &i2ed a$ount o& $e$ory 'ill -e allocated to t!e array -e&ore e2ecution o& t!e progra$. T!is $et!od o& allocating t!e $e$ory is 6no'n as Jstatic allocationE o& $e$ory. !- .and/ing Arra s ;or$ally &ollo'ing procedure is &ollo'ed &or progra$$ing so t!at5 -y c!anging only one Kde&ine state$ent 'e can run t!e progra$ &or arrays o& di&&erent si es. Kde&ine .II1 1+ int a=.II1>5 -=.II1>G ;o' i& 'e 'ant t!is progra$ to run &or an array o& 2++ ele$ents 'e need to c!ange 9ust t!e Kde&ine state$ent. 5. Initia/i0ing t)e Arra s8ne $et!od o& initiali ing t!e array $e$-ers is -y using t!e JforE loop. T!e &ollo'ing for loop initiali es 1+ ele$ents 'it! t!e *alue o& t!eir inde2. Kde&ine .II1 1+ $ain() L int arr=.II1>5 iG &or(i M +G i N .II1 G iOO ) L arr=i> M iG P P An array can also -e initiali ed directly as &ollo's. int arr=3> M L+5152PG An e2plicitly initiali ed array need not speci&y si e -ut i& speci&ied t!e nu$-er o& ele$ents pro*ided $ust not e2ceed t!e si e. I& t!e si e is gi*en and so$e ele$ents are not e2plicitly initiali ed t!ey are set to ero.

e.g. int arr=> M L+5152PG int arr1=5> M L+5152PG QR Initiali ed as L+51525+5+PRQ const c!ar aSarr3="> M TDanielTG QR 1,,8,G Daniel !as % ele$ents " in Daniel and a U+RQ To copy one array to anot!er eac! ele$ent !as to -e copied using &or structure. Any e2pression t!at e*aluates into an integral *alue can -e used as an inde2 into array. e.g. arr=getS*alue()> M so$e*alueG '- 1u/tidi2ensiona/ Arra s An array in which the elements need to be referred by two indices it is called a two dimensional array or a %matri$& and if it is referred using more than two indices, it will be 'ultidimensional Array. e.g. int arr=4>=3>G T!is is a t'o3di$ensional array 'it! 4 as ro' di$ension and 3 as a colu$n di$ension. 7- Initia/i0ation of *3o Di2ensiona/ Arra Vust li6e one3di$ensional arrays5 $e$-ers o& $atrices can also -e initiali ed in t'o 'ays using J&orE loop and directly. Initiali ation using nested loops is s!o'n -elo'. e.g. int arr=1+>=1+>G &or(int i M 1GiN M 1+GiOO) &or(int 9 M 1G 9N M 1+G9OO) L arr=i>=9> M iO9G

P ;o' let us see !o' $e$-ers o& $atrices are initiali ed directly. e.g. int arr=4>=3> M LL+5152P5L35455P5L"5%5(P5L)51+511PPG T!e nested -rac6ets are optional.

8- Pointers T!e co$puter $e$ory is a collection o& storage cells. T!ese locations are nu$-ered se@uentially and are called addresses. Pointers are addresses of memory location . Any variable, which contains an address is a pointer variable. Pointer *aria-les store t!e address o& an o-9ect5 allo'ing &or t!e indirect $anipulation o& t!at o-9ect. T!ey are used in creation and $anage$ent o& o-9ects t!at are dyna$ically created during progra$ e2ecution. +- Advantages and disadvantages of pointers Pointers are *ery e&&ecti*e '!en 12-112-212-3T!e data in one &unction can -e $odi&ied -y ot!er &unction -y passing t!e address. #e$ory !as to -e allocated '!ile running t!e progra$ and released -ac6 i& it is not re@uired t!erea&ter. Data can -e accessed &aster -ecause o& direct addressing. T!e only disad*antage o& pointers is5 i& not understood and not used properly can introduce -ugs in t!e progra$. 1"- Dec/aring and initia/i0ing pointers Pointers are declared using t!e (R) operator. T!e general &or$at isC dataStype Rptrna$eG

'!ere type can -e any o& t!e -asic data type suc! as integer5 &loat etc.5 or any o& t!e user3de&ined data type. Pointer na$e -eco$es t!e pointer o& t!at data type. e.g. int RiptrG c!ar RcptrG &loat R&ptrG T!e pointer iptr stores t!e address o& an integer. In ot!er 'ords it points to an integer5 cptr to a c!aracter and &ptr to a &loat *alue. 8nce t!e pointer *aria-le is declared it can -e $ade to point to a *aria-le 'it! t!e !elp o& an address (re&erence) operator(:). e.g. int nu$ M 1+24G int RiptrG iptr M :nu$G QQ iptr points to t!e *aria-le nu$. T!e pointer can !old t!e *alue o& +(;7<<)5 indicating t!at it points to no o-9ect at present. Pointers can never store a non address value. e.g. iptr1Mi*alG QQ in*alid5 i*al is not address.

A pointer o& one type cannot -e assigned t!e address *alue o& t!e o-9ect o& anot!er type. e.g. dou-le d*al5 Rdptr M :d*alG QQ allo'ed iptr M :d*al G QQnot allo'ed

11- Pointer Arit)2etic T!e pointer *alues stored in a pointer *aria-le can -e altered using arit!$etic operators. Fou can incre$ent or decre$ent pointers5 you can su-tract one pointer &ro$ anot!er5 you can add or su-tract integers to pointers -ut t'o pointers can not -e added as

it $ay lead to an address t!at is not present in t!e $e$ory. ;o ot!er arit!$etic operations are allo'ed on pointers t!an t!e ones discussed !ere. /onsider a progra$ to de$onstrate t!e pointer arit!$etic. e.g. K includeNstdio.!W $ain() L int a=>ML1+52+53+54+55+PG int RptrG int iG ptrMaG &or(iM+G iN5G iOO) L print&(XYdT5RptrOO)G P P 8utputC 1+ 2+ 3+ 4+ 5+ T!e addresses o& eac! $e$ory location &or t!e array JaE are s!o'n starting &ro$ 4++2 to 4++(. Initial address o& 4+++ is assigned to JptrE. T!en -y incre$enting t!e pointer *alue ne2t *alues are o-tained. Here eac! incre$ent state$ent incre$ents t!e pointer *aria-le -y 2 -ytes -ecause t!e si e o& t!e integer is 2 -ytes. T!e si e o& t!e *arious data types is s!o'n -elo' &or a 1"3-it $ac!ine. It $ay *ary &ro$ syste$ to syste$. c!ar int &loat long int dou-le (-ytes s!ort int 12- Arra of pointers 1-yte 2-ytes 4-ytes 4-ytes 2-ytes 4++( ptr33W 4+++ 1+ 4++2 2+ 4++4 4++" 5+ 3+ 4+

/onsider t!e declaration s!o'n -elo'C c!ar RA=3>MLXaT5 X-T5 XTe2t Aoo6TPG T!e e2a$ple declares JAE as an array o& c!aracter pointers. 1ac! location in t!e array points to string o& c!aracters o& *arying lengt!. Here A=+> points to t!e &irst c!aracter o& t!e &irst string and A=1> points to t!e &irst c!aracter o& t!e second string5 -ot! o& '!ic! contain only one c!aracter. !o'e*er5 A=2> points to t!e &irst c!aracter o& t!e t!ird string5 '!ic! contains ) c!aracters. 13- Passing para2eters to t)e functions 12-!12-5T!e di&&erent 'ays o& passing para$eters into t!e &unction areC Pass -y *alue( call -y *alue) Pass -y addressQpointer(call -y address)

In pass -y *alue 'e copy t!e actual argu$ent into t!e &or$al argu$ent declared in t!e &unction de&inition. T!ere&ore any c!anges $ade to t!e &or$al argu$ents are not returned -ac6 to t!e calling progra$. In pass -y address 'e use pointer *aria-les as argu$ents. Pointer *aria-les are particularly use&ul '!en passing to &unctions. T!e c!anges $ade in t!e called &unctions are re&lected -ac6 to t!e calling &unction. T!e progra$ uses t!e classic pro-le$ in progra$$ing5 s'apping t!e *alues o& t'o *aria-les. *oid *alSs'ap(int 25 int y) L int tG t M 2G 2 M yG y M tG P *oid addSs'ap(int R25 int Ry) QQ /all -y Address L int tG t M R2G R2 M RyG Ry M tG P QQ /all -y 0alue

*oid $ain() L int n1 M 255 n2 M 5+G print&(XUn Ae&ore call -y 0alue C T)G print&(XUn n1 M Yd n2 M YdT5n15n2)G *alSs'ap( n15 n2 )G print&(XUn A&ter call -y *alue C T)G print&(XUn n1 M Yd n2 M YdT5n15n2)G print&(XUn Ae&ore call -y Address C T)G print&(XUn n1 M Yd n2 M YdT5n15n2)G *alSs'ap( :n15 :n2 )G print&(XUn A&ter call -y *alue C T)G print&(XUn n1 M Yd n2 M YdT5n15n2)G P 8utputC Ae&ore call -y *alue C n1 M 25 n2 M 5+ A&ter call -y *alue C n1 M 25 n2 M 5+ QQ 2 M 5+5 y M 25 Ae&ore call -y address C n1 M 25 n2 M 5+ A&ter call -y address C n1 M 5+ n2 M 25 QQ2 M 5+5 y M 25 1!- ,e/ation 4et3een Pointers and Arra s Pointers and Arrays are related to eac! ot!er. All progra$s 'ritten 'it! arrays can also -e 'ritten 'it! t!e pointers. /onsider t!e &ollo'ingC int arr=> M L+51525354555"5%5(5)PG To access t!e *alue 'e can 'rite5 arr=+> or RarrG arr=1> or R(arrO1)G .ince JRE is used as pointer operator and is also used to dere&erence t!e pointer *aria-les5 you !a*e to 6no' t!e di&&erence -et'een t!e$ t!oroug!ly.

R(arrO1) $eans t!e address o& arr is increased -y 1 and t!en t!e contents are &etc!ed. RarrO1 $eans t!e contents are &etc!ed &ro$ address arr and one is added to t!e content. ;o' 'e !a*e understood t!e relation -et'een an array and pointer. T!e tra*ersal o& an array can -e $ade eit!er t!roug! su-scripting or -y direct pointer $anipulation. e.g. *oid print(int RarrS-eg5 int RarrSend) L '!ile(arrS-eg Z M arrSend) L print&(XYiT5Rarr)G OOarrS-egG P P *oid $ain() L int arr=> M L+51525354555"5%5(5)P print(arr5arrO))G P arrSend initiali es ele$ent past t!e end o& t!e array so t!at 'e can iterate t!roug! all t!e ele$ents o& t!e array. T!is !o'e*er 'or6s only 'it! pointers to array containing integers. 15- Scope ,u/es and Storage C/asses .ince 'e e2plained t!at t!e *alues in &or$al *aria-les are not re&lected -ac6 to t!e calling progra$5 it -eco$es i$portant to understand t!e scope and li&eti$e o& t!e *aria-les. T!e storage class deter$ines t!e li&e o& a *aria-le in ter$s o& its duration or its scope. T!ere are &our storage classesC 3 auto$atic 3 static 3 e2ternal 3 register

1-15-1 Auto2atic 5aria4/es Auto$atic *aria-les are de&ined 'it!in t!e &unctions. T!ey lose t!eir *alue '!en t!e &unction ter$inates. It can -e accessed only in t!at &unction. All *aria-les '!en declared 'it!in t!e &unction are5 -y de&ault5 Jauto$aticE. Ho'e*er5 'e can e2plicitly declare t!e$ -y using t!e 6ey'ord (automatic). e.g. *oid print() L auto int i M+G print&(XUn 0alue o& i -e&ore incre$enting is YdT5 i)G i M i O 1+G print&(XUn 0alue o& i a&ter incre$enting is YdT5 i)G P $ain() L print()G print()G print()G P 8utputC 0alue o& i -e&ore incre$enting is C + 0alue o& i a&ter incre$enting is C 1+ 0alue o& i -e&ore incre$enting is C + 0alue o& i a&ter incre$enting is C 1+ 0alue o& i -e&ore incre$enting is C + 0alue o& i a&ter incre$enting is C 1+ 1-15-2- Static 5aria4/es .tatic *aria-les !a*e t!e sa$e scope s auto$atic *aria-les5 -ut5 unli6e auto$atic *aria-les5 static *aria-les retain t!eir *alues o*er nu$-er o& &unction calls. T!e li&e o& a static *aria-le starts5 '!en t!e &irst ti$e t!e &unction in '!ic! it is declared5 is e2ecuted

and it re$ains in e2istence5 till t!e progra$ ter$inates. T!ey are declared 'it! t!e 6ey'ord static. e.g. *oid print() L static int i M+G print&(XUn 0alue o& i -e&ore incre$enting is YdT5 i)G i M i O 1+G print&(XUn 0alue o& i a&ter incre$enting is YdT5 i)G P $ain() L print()G print()G print()G P 8utputC 0alue o& i -e&ore incre$enting is C + 0alue o& i a&ter incre$enting is C 1+ 0alue o& i -e&ore incre$enting is C 1+ 0alue o& i a&ter incre$enting is C 2+ 0alue o& i -e&ore incre$enting is C 2+ 0alue o& i a&ter incre$enting is C 3+ It can -e seen &ro$ t!e a-o*e e2a$ple t!at t!e *alue o& t!e *aria-le is retained '!en t!e &unction is called again. It is allocated $e$ory and is initiali ed only &or t!e &irst ti$e.

1-15-3- 67terna/ 5aria4/es Di&&erent &unctions o& t!e sa$e progra$ can -e 'ritten in di&&erent source &iles and can -e co$piled toget!er. T!e scope o& a glo-al *aria-le is not li$ited to any one &unction5 -ut is e2tended to all t!e &unctions t!at are de&ined a&ter it is declared. Ho'e*er5 t!e scope o& a glo-al *aria-le is li$ited to only t!ose &unctions5 '!ic! are in t!e sa$e &ile

scope. I& 'e 'ant to use a *aria-le de&ined in anot!er &ile5 'e can use e$tern to declare t!e$. e.g. QQ 4I<1 1 g is glo-al and can -e used only in $ain() and QQ QQ &n1()G int g M +G *oid $ain() L C C P *oid &n1() L C C P QQ 4I<1 2 I& t!e *aria-le declared in &ile 1 is re@uired to -e used in &ile 2 t!en it is to -e declared as an e2tern. e2tern int g M +G *oid &n2() L C C P *oid &n3() L C P

1-15-!- ,egister 5aria4/e

/o$puters !a*e internal registers5 '!ic! are used to store data te$porarily5 -e&ore any operation can -e per&or$ed. Inter$ediate results o& t!e calculations are also stored in registers. 8perations can -e per&or$ed on t!e data stored in registers $ore @uic6ly t!an on t!e data stored in $e$ory. T!is is -ecause t!e registers are a part o& t!e processor itsel&. I& a particular *aria-le is used o&ten &or instance5 t!e control *aria-le in a loop5 can -e assigned a register5 rat!er t!an a *aria-le. T!is is done using t!e 6ey'ord register. Ho'e*er5 a register is assigned -y t!e co$piler only i& it is &ree5 ot!er'ise it is ta6en as auto$atic. Also5 glo-al *aria-les cannot -e register *aria-les. e.g. *oid loop&n() L register int iG &or(iM+G iN 1++G iOO) L print&(XYdT5 i)G P P

1'- D na2ic a//ocation and de%a//ocation of 2e2or #e$ory &or syste$ de&ined *aria-les and arrays are allocated at co$pilation ti$e. T!e si e o& t!ese *aria-les cannot -e *aried during run ti$e. T!ese are called Jstatic data structures). T!e disad*antage o& t!ese data structures is t!at t!ey re@uire &i2ed a$ount o& storage. 8nce t!e storage is &i2ed i& t!e progra$ uses s$all $e$ory out o& it re$aining locations are 'asted. I& 'e try to use $ore $e$ory t!an declared o*er&lo' occurs. I& t!ere is an unpredicta-le storage re@uire$ent5 se@uential allocation is not reco$$ended. T!e process o& allocating $e$ory at run ti$e is called (dynamic allocation). Here5 t!e re@uired a$ount o& $e$ory can -e o-tained &ro$ &ree $e$ory called JHeapE5 a*aila-le &or t!e user. T!is &ree $e$ory is stored as a list called (Availability *ist). Betting a -loc6 o& $e$ory and returning it to t!e a*aila-ility list5 can -e done -y using &unctions li6eC 12-'12-7- $alloc() 12-8- calloc() 12-+- &ree()

17- 8unction 2a//oc(si0e) T!is &unction is de&ined in t!e !eader &ile Nstdli-.!W and Nalloc.!W. T!is &unction allocates a -loc6 o& Jsi+e) -ytes &ro$ t!e !eap or a*aila-ility list. 8n success it returns a pointer o& type J*oidE to t!e allocated $e$ory. De $ust typecast it to t!e type 'e re@uire li6e int5 &loat etc. I& re@uired space does not e2ist it returns ;7<<. .ynta2C ptr M (dataStypeR) $alloc(si e)G '!ere 12-1"- ptr is a pointer *aria-le o& type dataStype. 12-11- dataStype can -e any o& t!e -asic data type5 user de&ined or deri*ed data type. 12-12- si e is t!e nu$-er o& -ytes re@uired. e.g. ptr M(intR)$alloc(si eo&(int)Rn)G allocates $e$ory depending on t!e *alue o& *aria-le n. K includeNstdio.!W K includeNstring.!W K includeNalloc.!W K includeNprocess.!W $ain() L c!ar RstrG i&((strM(c!arR)$alloc(1+))MM;7<<) QR allocate $e$ory &or string RQ L print&(XUn 87T 84 #1#8,FT)G e2it(1)G QR ter$inate t!e progra$ RQ P strcpy(str5THelloT)G print&(XUn strM Ys X5str)G &ree(str)G P QR copy !ello into str RQ QR display str RQ QR &ree $e$ory RQ

In t!e a-o*e progra$ i& $e$ory is allocated to t!e str5 a string !ello is copied into it. T!en str is displayed. D!en it is no longer needed5 t!e $e$ory occupied -y it is released -ac6 to t!e $e$ory !eap. 18- 8unction ca//oc(n9si0e) T!is &unction is de&ined in t!e !eader &ile Nstdli-.!W and Nalloc.!W. T!is &unction allocates $e$ory &ro$ t!e !eap or a*aila-ility list. I& re@uired space does not e2ist &or t!e ne' -loc6 or n5 or si e is ero it returns ;7<<. .ynta2C ptr M (dataStypeR) $alloc(n5si e)G '!ere 12-13- ptr is a pointer *aria-le o& type dataStype. 12-1!- dataStype can -e any o& t!e -asic data type5 user de&ined or deri*ed data type. 12-15- si e is t!e nu$-er o& -ytes re@uired. 12-1'- n is t!e nu$-er o& -loc6s to -e allocated o& si e -ytes. and a pointer to t!e &irst -yte o& t!e allocated region is returned. e.g. K includeNstdio.!W K includeNstring.!W K includeNalloc.!W K includeNprocess.!W $ain() L c!ar Rstr M ;7<<G strM(c!arR)calloc(1+5si eo&(c!ar))G QR allocate $e$ory &or string RQ i&(str MM ;7<<)G L print&(XUn 87T 84 #1#8,FT)G e2it(1)G QR ter$inate t!e progra$ RQ P strcpy(str5THelloT)G QR copy !ello into str RQ

print&(XUn strM Ys X5str)G &ree(str)G P 1+- 8unction free(4/oc$)

QR display str RQ QR &ree $e$ory RQ

T!is &unction &rees allocated -loc6 o& $e$ory using $alloc() or calloc(). T!e progra$$er can use t!is &unction and de3allocate t!e $e$ory t!at is not re@uired any $ore -y t!e *aria-le. It does not return any *alue. 17- Dang/ing pointer pro4/e2De can allocate $e$ory to t!e sa$e *aria-le $ore t!an once. T!e co$piler 'ill not raise any error. Aut it could lead to -ugs in t!e progra$. De can understand t!is pro-le$ 'it! t!e &ollo'ing e2a$ple. K includeNstdio.!W K includeNalloc.!W $ain() L int RaG aM (intR)$alloc(si eo&(int))G Ra M 1+G aM (intR)$alloc(si eo&(int))G Ra M 2+G P In t!is progra$ seg$ent $e$ory allocation &or *aria-le JaE Is done t'ice. In t!is case t!e *aria-le contains t!e address o& t!e $ost recently allocated $e$ory5 t!ere-y $a6ing t!e earlier allocated $e$ory inaccessi-le. .o5 $e$ory location '!ere t!e *alue 1+ is stored5 is inaccessi-le to any o& t!e application and is not possi-le to &ree it so t!at it can -e reused. To see anot!er pro-le$5 consider t!e ne2t progra$ seg$entC $ain() L int RaG 3333W 3333W 1+ 2+

aM (intR)$alloc(si eo&(int))G Ra M 1+G &ree(a)G

3333W

1+ , [

P Here5 i& 'e de3allocate t!e $e$ory &or t!e *aria-le JaE using &ree(a)5 t!e $e$ory location pointed -y JaE is returned to t!e $e$ory pool. ;o' since pointer JaE does not contain any *alid address 'e call it as (Dangling Pointer). I& 'e 'ant to reuse t!is pointer 'e can allocate $e$ory &or it again. 18- Structures A structure is a deri*ed data type. It is a co$-ination o& logically related data ite$s. 7nli6e arrays5 '!ic! are a collection o& si$ilar data types5 structures can contain $e$-ers o& di&&erent data type. T!e data ite$s in t!e structures generally -elong to t!e sa$e entity5 li6e in&or$ation o& an e$ployee5 players etc. T!e general &or$at o& structure declaration isC struct tag L type $e$-er1G type $e$-er2G type $e$-er3G C C P*aria-lesG De can o$it t!e *aria-le declaration in t!e structure declaration and de&ine it separately as &ollo's C struct tag *aria-leG e.g. struct Account L int accnu$G c!ar acctypeG

c!ar na$e=25>G &loat -alanceG PG De can declare structure *aria-les as C struct Account oldcustG De can re&er to t!e $e$-er *aria-les o& t!e structures -y using a dot operator (.). e.g. ne'cust.-alance M 1++.+ print&(XYsT5 oldcust.na$e)G De can initiali e t!e $e$-ers as &ollo's C e.g. Account custo$er M L1++5 J'E5 JDa*idE5 "5++.++PG De cannot copy one structure *aria-le into anot!er. I& t!is !as to -e done t!en 'e !a*e to do $e$-er3'ise assign$ent. De can also !a*e nested structures as s!o'n in t!e &ollo'ing e2a$pleC struct Date L int dd5 $$5 yyG PG struct Account L int accnu$G c!ar acctypeG c!ar na$e=25>G &loat -alanceG struct Date d1G PG ;o' i& 'e !a*e to access t!e $e$-ers o& date t!en 'e !a*e to use t!e &ollo'ing $et!od.

Account c1G c1.d1.ddM21G De can pass and return structures into &unctions. T!e '!ole structure 'ill get copied into &or$al *aria-le. De can also !a*e array o& structures. I& 'e declare array to account structure it 'ill loo6 li6e5 Account a=1+>G 1*ery t!ing is sa$e as t!at o& a single ele$ent e2cept t!at it re@uires su-script in order to 6no' '!ic! structure 'e are re&erring to. De can also declare pointers to structures and to access $e$-er *aria-les 'e !a*e to use t!e pointer operator 3W instead o& a dot operator. Account RaptrG print&(XYsT5aptr3Wna$e)G A structure can contain pointer to itsel& as one o& t!e *aria-les5 also called sel&3 re&erential structures. e.g. struct in&o L int i5 95 6G in&o Rne2tG PG In s!ort 'e can list t!e uses o& t!e structure asC 12-17- ,elated data ite$s o& dissi$ilar data types can -e logically grouped under a co$$on na$e. 12-18- /an -e used to pass para$eters so as to $ini$i e t!e nu$-er o& &unction argu$ents. 12-1+- D!en $ore t!an one data !as to -e returned &ro$ t!e &unction t!ese are use&ul. 12-2"- #a6es t!e progra$ $ore reada-le.

1+- 6nu2erated Constants 1nu$erated constants ena-le t!e creation o& ne' types and t!en de&ine *aria-les o& t!ese types so t!at t!eir *alues are restricted to a set o& possi-le *alues. T!ere synta2 isC enu$ identi&ier Lc15c25...P=*arSlist>G '!ere 12-21- enu$ is t!e 6ey'ord. 12-22- identi&ier is t!e user de&ined enu$erated data type5 '!ic! can -e used to declare t!e *aria-les in t!e progra$. 12-23- Lc15c25...P are t!e na$es o& constants and are called enu$eration constants. 12-2!- *arSlist is an optional list o& *aria-les. e.g. enu$ /olourL,1D5 A<715 B,11;5 DHIT15 A<A/\PG /olour is t!e na$e o& an enu$erated data type. It $a6es ,1D a sy$-olic constant 'it! t!e *alue +5 A<71 a sy$-olic constant 'it! t!e *alue 1 and so on. 1*ery enu$erated constant !as an integer *alue. I& t!e progra$ doesnEt speci&y ot!er'ise5 t!e &irst constant 'ill !a*e t!e *alue +5 t!e re$aining constants 'ill count up -y 1 as co$pared to t!eir predecessors. Any o& t!e enu$erated constant can -e initialised to !a*e a particular *alue5 !o'e*er5 t!ose t!at are not initialised 'ill count up'ards &ro$ t!e *alue o& pre*ious *aria-les. e.g. enu$ /olourL,1D M 1++5 A<715 B,11; M 5++5 DHIT15 A<A/\ M 1+++PG T!e *alues assigned 'ill -e ,1D M 1++5A<71 M 1+15B,111; M 5++5DHIT1 M 5+15A<A/\ M 1+++ Fou can de&ine *aria-les o& type /olour5 -ut t!ey can !old only one o& t!e enu$erated *alues. In our case ,1D5 A<715 B,111;5 DHIT15 A<A/\ . Fou can declare o-9ects o& enu$ types. e.g.

enu$ DaysL.7;5 #8;5 T715 D1D5 TH75 4,I5 .ATPG Days dayG Day M .7;G Day M 3G QQ error int and day are o& di&&erent types Day M !elloG QQ !ello is not a $e$-er o& Days. 1*en t!oug! enu$ sy$-olic constants are internally considered to -e o& type unsigned int 'e cannot use t!e$ &or iterations. e.g. enu$ DaysL.7;5 #8;5 T715 D1D5 TH75 4,I5 .ATPG &or(enu$ i M .7;G iN.ATG iOO) QQnot allo'ed. T!ere is no support &or $o*ing -ac6'ard or &or'ard &ro$ one enu$erator to anot!er. Ho'e*er '!ene*er necessary5 an enu$eration is auto$atically pro$oted to arit!$etic type.

e.g. i&( #8; W +) L print&(X #onday is greaterT)G P int nu$ M 2R#8;G 2"- :nions A union is also li6e a structure5 e2cept t!at only one *aria-le in t!e union is stored in t!e allocated $e$ory at a ti$e. It is a collection o& $utually e2clusi*e *aria-les5 '!ic! $eans all o& its $e$-er *aria-les s!are t!e sa$e p!ysical storage and only one *aria-le is de&ined at a ti$e. T!e si e o& t!e union is e@ual to t!e largest $e$-er *aria-les. A union is de&ined as &ollo'sC union tag L type $e$*ar1G

type $e$*ar2G type $e$*ar3G C C PG A union *aria-le o& t!is data type can -e declared as &ollo's5 union tag *aria-leSna$eG e.g. union utag L int nu$G c!ar c!G PG union tag &&G T!e a-o*e union 'ill !a*e t'o -ytes o& storage allocated to it. T!e *aria-le nu$ can -e accessed as &&.su$ and c! is accessed as &&.c!. At any ti$e5 only one o& t!ese t'o *aria-les can -e re&erred to. Any c!ange $ade to one *aria-le a&&ects anot!er. T!us unions use $e$ory e&&iciently -y using t!e sa$e $e$ory to store all t!e *aria-les5 '!ic! $ay -e o& di&&erent types5 '!ic! e2ist at $utually e2clusi*e ti$es and are to -e used in t!e progra$ only once. In t!is c!apter 'e !a*e studies so$e ad*anced &eatures o& /. De !a*e seen !o' t!e &le2i-ility o& language allo'ed us to de&ine a user3de&ined *aria-le5 is a co$-ination o& di&&erent types o& *aria-les5 '!ic! -elong to so$e entity. De also studies arrays and pointers in detail. T!ese are *ery use&ul in t!e study o& *arious data structures.

Session 2 Introduction to Data structures During this session you will learn about:

2. 3. 4. 5. 6. 7.

Data ob-ects and Data structures. .lassification of data structures. /mplementation of data structures. Abstract data type. Algorithm and pseudo codes. .omple$ity of algorithm.

2-1- Introduction Data structures5 is one o& t!e $ost i$portant su-9ect5 '!ic! is re@uired -y all t!e so&t'are progra$$ers. As a progra$$er5 'e 'ould -e !andling t!e data in !uge @uantity. T!e data 'e are gi*en5 re@uires to -e stored in t!e $e$ory. T!e $e$ory s!ould -e used e&&iciently. T!e data 'ill -e !andled on t!e -asis o& its type. It could -e an integer5 real5 c!aracter etc. T!ere could -e e*en t!e co$-ination o& t!e data5 result in so$e ne' type5 li6e structures5 unions etc '!ic! 'ere co*ered in t!e pre*ious session. 2-2- Data ;4<ects = Data Structures DA0A 123!.0 is a set of elements, say D. T!is D $ay or $ay not -e &inite5 &or e2a$ple5 '!en data o-9ect is set o& real nu$-ers is in&inite and '!en it is a set o& nu$eric digits it is &inite. DA0A S04U.0U4! contains the data ob-ect along with the set of operations, which will be performed on them, or data structure contains the information about the manner in which these data ob-ects are related. 0he data structures deal with the study of how data is organi+ed in the memory, how efficiently it can be retrieved and manipulated. T!ey can -e classi&ied into 8. Pri$iti*e Data structures. 9. ;on Pri$iti*e Data structures.

2-3- Pri2itive Data structures 0hese are the data structures that can be manipulated directly by machine instructions. T!e integer5 real5 c!aracter etc.5 are so$e o& pri$iti*e data structures. In /5 t!e di&&erent pri$iti*e data structures are int, float, char and double.

2-!- >on Pri2itive Data structures T!ese data structures cannot -e $anipulated directly -y $ac!ine instructions. Arrays5 lin6ed lists5 trees etc.5 are so$e non3pri$iti*e data structures. T!ese data structures can -e &urt!er classi&ied into Jlinear) and (non linear) data structures. 0he data structures that show the relationship of logical ad-acency between the elements are called linear data structures. 1therwise they are called non linear data structures. Di&&erent linear data structures are stac65 @ueue5 linear lin6ed lists suc! as singly lin6ed list5 dou-ly lin6ed list etc. Trees5 grap!s etc are non3linear data structures. 2-5- I2p/e2entation of t)e Data Structures D!en 'e de&ine t!e data structure5 'e also gi*e t!e &unctions or t!e rules used &or !andling o& t!e data and its logical andQor p!ysical relation. T!is can -e considered as conceptual !andling o& data &or e&&ecti*e 'or6ing. Aut *ery o&ten 'e &ace li$itations o& a particular language or -y t!e a*aila-le data i.e. its type and si e. D!en t!ese co$e into picture along 'it! t!e de&ined data structure5 'e $ay c!ose so$e ot!er a*aila-le &or$ &or !andling t!e data along 'it! all t!e restrictions i$posed on it. /onsider t!e co$$on e2a$ple o& t!e ?7171. It 'ill -e e*ery day e2perience t!at '!ene*er 'e are in @ueue 'e &ollo' all t!e rules o& t!e @ueue. De are a'are t!at t!e &irst person in t!e @ueue 'ill -e t!e &irst one to lea*e it. De 'ill not allo' anyone to enter t!e @ueue in -et'een t!e &irst and t!e last person. Fou cannot lea*e t!e @ueue and cannot searc! &or so$eone. D!en 'e t!in6 o& processing t!e data t!e *ery &irst t!ing t!at co$es to our $ind is t!at5 'e s!ould process t!e data in sa$e se@uence in '!ic! it arri*es and !ence &or storing t!e data 'e de&ine t!e data structure called ?7171.

T!e rules to -e &ollo'ed -y t!e @ueue are C 10.T!e data can -e re$o*ed &ro$ one end5 called as t!e &ront. 11.T!e ne' data s!ould -e al'ays added at t!e ot!er end called rear. 12.It is possi-le t!at t!ere is no data in t!e @ueue5 '!ic! indicates @ueue e$pty condition.

13.It is possi-le t!at t!ere is no space in t!e @ueue &or data to -e stored '!ic! indicates @ueue &ull condition. ;o' i& 'e t!in6 o& actually using t!e concept in our progra$ t!en it is necessary to store t!ese data ite$s. De s!ould re$e$-er '!ic! is t!e &irst and '!ic! is t!e last data ite$. I& 'e use di&&erent *aria-le na$es &or eac! ite$ t!ey 'ill not loo6 as i& t!ey are related. T!e only $et!od to store related ite$s5 '!ic! 'e all 6no' -y t!is ti$e5 is using an Array. T!e array can -e used to i$ple$ent @ueue. In case o& arrays5 deletion and addition can -e $ade at any position. 4or @ueues5 'e !a*e to i$pose so$e restrictions. De 'ill !a*e to re$e$-er t'o positions indicating t!e &irst and t!e last positions o& t!e @ueue. D!ene*er an ite$ is re$o*ed t!e &irst position 'ill c!ange to its ne2t. I& our &irst position is -eyond t!e last5 t!e @ueue 'ill not contain any data ite$s. T!e deletion o& an ele$ent &ro$ t!e @ueue 'ill -e logical deletion. I& 'e o-ser*e t!e array5 t!en all t!e ele$ents are p!ysically a*aila-le all t!e ti$e. T!e sa$e data structure can also -e i$ple$ented -y anot!er data structure 6no'n as <I;\1D <I.T. In s!ort 'e say t!at i$ple$enting data structure d1 using anot!er data structure d25 is $apping &ro$ d1 to d2. 2-'- A4stract Data t pe A data structure is a set o& do$ains D5 a designated do$ain P5 a set o& &unctions 4 and set o& a2io$s B. A triplet (D545B) denotes t!e data structure d. T!e triplet is re&erred to as a-stract data type (ADT). It is a-stract -ecause t!e a2io$s in t!e triple do not gi*e any idea a-out t!e representation. De&ining t!e data structure is a continuous process -ecause at t!e initial stage 'e can design a data structure5 and also 'e indicate as '!at it s!ould do. In t!e later stages o& t!e re&ine$ent 'e try to &ind t!e 'ays in '!ic! it can -e done or !o' it can -e ac!ie*ed. T!us it is t!e total process o& speci&ication and i$ple$entation. T!e idea &or representing o& data5 relation in t!e data o-9ects and t!e tas6s to -e per&or$ed 'ill -e t!e speci&ication o& t!e data structure. D!en 'e actually try to use all t!e concepts t!en 'e decide as !o' to ac!ie*e eac! goal5 '!ic! set -y eac! &unction. T!is 'ill -e t!e i$ple$entation p!ase.

2-7- A/gorit)2 and pseudo code D!ene*er 'e need to sol*e a pro-le$ it is a -etter approac! to &irst 'rite do'n t!e solution in algorit!$ or pseudo codes. 8nce t!e logic and data structures to -e used are decided 'e can 'rite algorit!$ or a pseudo code. <ater 'e can i$ple$ent t!e$ into a progra$ o& a particular language. Algorithm is a set by step solution to a problem written in !nglish alone or with some programming language constructs. Pseudo code is algorithm written in a particular programming language that will be used to implement the algorithm. 2-8- Co2p/e7it of A/gorit)2s D!en a progra$ is 'ritten5 it is e*aluated on $any criteria5 li6e satis&actory results5 $ini$u$ code5 opti$u$ logic etc. T!e co$ple2ity o& t!e algorit!$5 '!ic! is used5 'ill depend on t!e nu$-er o& state$ents e2ecuted. T!oug! t!e e2ecution &or eac! state$ent is di&&erent5 'e can roug!ly c!ec6 as !o' $any ti$es eac! state$ent is e2ecuted. D!ene*er 'e e2ecute a conditional state$ent5 'e 'ill -e s6ipping so$e state$ents or 'e $ig!t repeat so$e state$ents. Hence t!e total nu$-er o& state$ents e2ecuted 'ill depend on conditional state$ents. At t!is stage 'e can roug!ly esti$ate t!at t!e co$ple2ity is t!e nu$-er o& ti$es t!e condition is e2ecuted. e.g. &or(iM+G iNnG iOO) L print&(XYdT5i)GP T!e output is &ro$ + to n31. De can easily say t!at it !as -een e2ecuted n ti$es. T!e condition '!ic! is c!ec6ed !ere is iNn. It is e2ecuted nO1 ti$es 3 n ti$es '!en it is true and once '!en it is &alse. Hence t!e total nu$-er o& state$ents e2ecutes is 2nO1. Also t!e state$ent iM+ is e2ecuted once and iOO is e2ecuted n ti$es. T!e total M 1O(nOZ)O(n)O(n) M 3n O 2 I& 'e ignore t!e constants5 'e say t!at t!e co$ple2ity is o& t!e order o& n. T!e notation used is -ig38. i.e. 8(n).

67ercises ? 4ind t!e nu$-er o& ti$es &or '!ic! eac! state$ent is e2ecuted. 14.iM2G '!ile( i N n) L &or( i M +G i N nG iOO) L 6M6O9G P iMiO2G P 15.&or( i M+G iNnG iOO) L &or(9M+G 9NiG 9OO) L print&(X 1nter t!e nu$ X)G scan&(XY&T5:p=i>=9>G)E P P During this session you will learn about: Some applications of Arrays. Polynomial representation for one variable and two variables. String 5andling Array of characters. 0wo dimensional arrays 'atrices. Sparse 'atrices. 'ultidimensional Arrays.

3-1- Introduction All t!e discussion in t!is -oo6 'ill -e in conte2t to t!e language /. 8ur $ain interest is to use $e$ory e&&ecti*ely. De !a*e already learnt in t!e &irst session t!at '!en 'e need $any data $e$-ers o& sa$e type5 '!ic! are related5 'e use arrays to represent t!e$. ;o' let us discuss so$e applications '!ere arrays can -e used.

3-2- 6va/uation of Po/ no2ia/s 3-2-1- Po/ no2ia/ in a sing/e varia4/e Polyno$ial is a e2pression o& type C P(2) M P+ O P1 ]^1 O P2 ]^2 O . . . . O Pn ]^n. D!ere n is called t!e degree o& t!at polyno$ial. 8ne t!ing is *ery clear &ro$ t!e e2pression5 '!ic! contain only one *aria-le 25 is t!at 'e 'ill re@uire storing &or eac! ite$ its coe&&icient and its po'er. T!e &ollo'ing structure 'ould ser*e t!e purposeC struct polyno L &loat coe&G int p'GP T!en 'e $ay proceed 'it! t!e declaration o& an array o& structures. struct polyno P=.II1>G Array as a data structure 'ill !a*e $any applications and also *ery i$portant &acilities. Aut si e li$itations 'ill appear as a set-ac6 &or t!is c!oice. T!e degree o& t!e polyno$ial 'ill decide t!e si e o& t!e array. ( si e o& t!e polyno$ial ) M (degree o& polyno$ial ) O 1 Aut as 'e are going to input any polyno$ial5 t!e si e i.e. t!e degree is not 6no'n. Hence let us decide t!e array si e -igger t!an t!e nor$al *alue polyno$ial say 1+ or 1++. De !a*e to 6eep t!is li$itation in $ind '!en using t!e progra$. ;o' also o-ser*e t!at t!e degree o& eac! ter$ is an integer and so is t!e inde2 o& t!e array. ;o' 'e $ay say t!at t!e position o& t!e coe&&icient in t!e array itsel& is t!e degree o& 2 'it! it. T!en 'e $ay not e*en re@uire t!e array o& structures5 -ut e*en a &loat array o& coef 'ill 'or6. e.g. coe&=+> is coe&&icient o& 2^+ coe&=1> is coe&&icient o& 2^1 C

C coe&=i> is coe&&icient o& 2^i T!e input $ay -e ta6en in t'o 'aysC 1. As6 &or coe&&icient5 e*ery ti$e display t!e po'er o& 2 i.e. Please input t!e coe&&icient o& =2^+>C Please input t!e coe&&icient o& =2^1>C Here it 'ill -e totally t!e userEs responsi-ility to gi*e t!e coe&&icient as ero i& a particular po'er is a-sent. 2. As6 t!e user to input t!e po'er and coe&&icient. Here t!e user s!ould care&ully input all *alues 'it!out repeating any po'er -ecause 'e 'ill -e directly storing t!e coe&&icient at t!e po'er location. Here user doesnEt !a*e to input all t!e ero coe&&icients. It is t!e progra$$erEs responsi-ility no' to initiali e t!e array 'it! eroes so t!at i& a particular po'er is not entered t!en its coe&&icient is auto$atically ero. ;o'5 'e can declare t!e array as C &loat coe&=.II1>G 6.7.7. Polynomial in 0wo variables ;o' i& 'e are gi*en a polyno$ial !a*ing t'o *aria-les per ter$5 i.e. &or e2a$ple C P( 25 y) M 323y 422y4 O "2 %y3 O 1( 2y Here 'e cannot e$ploy t!e pre*ious $et!od and so 'e !a*e to go -ac6 &or declaring a structure as &ollo's C struct poly2 L &loat coe&G int p'25 p'yG PG T!e &ollo'ing is t!e progra$5 '!ic! deals 'it! t!e polyno$ials in one *aria-le. It is i$ple$ented using array o& structures. T!e ter$s are stored in t!e se@uence gi*en -y t!e user. Hence 'e !a*e to scan t!e second polyno$ial to $atc! t!e po'er '!en 'e

per&or$ addition. Also5 'e are re@uired to re$e$-er '!et!er a particular ter$ is added or not. De can use a &lag &or t!is purpose. Progra2 3-2-2- Addition of po/ no2ia/s in sing/e varia4/e K include Nstdio.!W K include Nconio.!W K de&ine si e 1+ int n15 n25 n3G struct poly2 L &loat coe&G QRcoe&&icient o& eac! ter$5 'it! sign RQ int p'5 &lagG Pp1=si e>5p2=si e>5p3=si e>G *oid readSpoly( struct poly2 p=>5 int n)G QR to read polyno$ial o& si e nRQ int addSpoly(struct poly2 p1=>5int n15 struct poly2 p2=>5 int n25 struct poly2 p3=>)G int &indSpos( struct poly2 p=>5 int n5 int po'er)G *oid printSpoly( struct poly2 p=>5 int n)G &loat p'r( &loat 25 int n)G QR to e*aluate 2 to t!e po'er n RQ $ain() L clrscr()G print&(X1nter t!e no o& ter$sCT)G scan&(XYdT5:n1)G print&(XUn 1nter t!e data &or &irst polyno$ialUnT)G readSpoly(p15n1)G print&(X1nter t!e no o& ter$sCT)G scan&(XYdT5:n2)G

print&(XUn 1nter t!e data &or second polyno$ialUnT)G readSpoly(p25n2)G n3M addSpoly(p15n15p25n25p3)G print&(X T!e &irst polyno$ial is_.UnT)G printSpoly(p15n1)G print&(X T!e second polyno$ial is_.UnT)G printSpoly(p25n2)G print&(X T!e resultant polyno$ial is_.UnT)G printSpoly(p35n3)G P QR $ain ends RQ QRRRRRRRRRRR &unction to read polyno$ial RRRRRRRRRRRRQ *oid readSpoly(struct poly2 p=>5 int n) L int iM+G &or( iM +G iNnG iOO) L print&(X Bi*e po'er_T)G scan&(XYdT5:p=i>.p')G print&(XBi*e coe&&_T)G scan&(XYdT5 :p=i>.coe&)G p=i>.&lagM+G P P QRRRRRRRRRRRRRR Addition o& polyRRRRRRRRRRRRRRRRRRRRRQ int addSpoly(struct poly2 p1=>5int n15struct poly2 p2=>5 int n25struct poly2 p3=>) L int iM+5 9M+56M+5n3M+G n3 M n1G do

L 9 M &indSpos(p25n25p1=i>.p')G QR !a*ing po'erRQ QR p1=i>.p' in p2RQ i&( 9 MM 31) QR 31 indicates it is a-sent RQ L p3=6>.p' M p1=i>.p'G p3=6>.coe& M p1=i>.coe&G p1=iOO>.&lag M 1G P else L p3=6>.p' M p1=i>.p'G QR'!en t!e ter$ is RQ present RQ p3=6>.coe& M p1=i>.coe&GQR coe& addedRQ p1=iOO>.&lag M 1G QR &lag set to 1RQ p2=9OO>.&lag M 1G QR &lag indicates t!at QR t!e tern !asRQ QR-een considered RQ 6OOG P P'!ile( 9 Nn1)G 9M +G '!ile( 9 N n2) L i&(p2=9>.&lag M M +) QR searc! &or t!e ter$ in p2 RQ QR '!ose &lag is + RQ L QR add suc! a ter$ RQ p3=6>.p' M p2=9>.p'G p3=6>.coe& M p2=9>.coe&G 6OOG n3OOG P 9OOG P return ( n3)G P QRR &ind t!e position o& t!e ter$5 '!ic! !as t!e gi*en po'er RRQ

int &indSpos( struct poly2 p=>5 int n5 int po'er) L int i M+G '!ile( i N n) L i&( p=i>.p' MM po'er) return(i)G else iOOG P return(31)G P QRRRRRRRRRRRRR prints t!e polyno$ial RRRRRRRRRRRRRRRRRRQ *oid printSpoly( struct poly2 p=>5 int n) L int iM+G &or(iM+GiNnGiOO) i&(p=i>.coe& ZM + ) print&(XY2.2&=2^Yd>OT5 p=i>.coe&5p=i>.p')G print&(XY2.2&=2^Yd>UnT5 p=i>.coe&5p=i>.p')G P QRRRRRRRRto e*aluate 2 to t!e po'er n RRRRRRRRRRRRRRRRRQ QR ( considers positi*e as 'ell as negati*e po'ers ) RQ &loat p'r( &loat 25 int n) L int iM+5 $G &loat pM1G i&(n N+ ) $M 3nG else $MnG '!ile(i N $) L

pMpR2G iOOG P i&( n WM+) return pG else return (1Qp)G P 8utputC 1nter t!e no o& ter$sC 3 1nter t!e data &or &irst polyno$ial Bi*e po'er_1 Bi*e coe&_ 3.++++++ Bi*e po'er_4 Bi*e coe&_ 34.++++++ Bi*e po'er_3 Bi*e coe&_ 2.++++++ 1nter t!e no o& ter$sC 2 1nter t!e data &or second polyno$ial Bi*e po'er_4 Bi*e coe&_ 31.++++++ Bi*e po'er_2 Bi*e coe&_ 1.++++++ T!e &irst poly is_. 3.++=2^1> O 34.++=2^4> O 2.++=2^3> O +.++=2^+> T!e second poly is_. 31.++=2^4> O 1.++=2^2> O +.++=2^+> T!e resultant polyno$ial is.. . 3.++=2^1> O 35.++=2^4> O 2.++=2^3> O 1.++=2^2>O +.++=2^+> Fou can try ot!er operations li6e su-traction and $ultiplication o& t'o polyno$ials on t!ese. Fou $ay 'rite progra$s to per&or$ t!ese &unctions on polyno$ials 'it! t'o *aria-les.

3-3- Strings A string is an array of characters. T!ey can contain any A./II c!aracter and are use&ul in $any operations. A c!aracter occupies a single -yte. T!ere&ore a string o& lengt! ; c!aracters re@uires ; -ytes o& $e$ory. .ince strings do not use -ounding inde2es it is i$portant to $ar6 t!eir end. D!ene*er enter 6ey is pressed -y t!e user t!e co$piler treats it as t!e end o& string. It puts a special c!aracter JU+E (;7<<) at t!e end and uses it as t!e end o& t!e string $ar6er t!ere on'ards. D!en t!e &unction scan&() is used &or reading t!e string5 it puts a JU+E c!aracter '!en it recei*es space. Hence i& a string $ust contain a space in it 'e s!ould use t!e &unction gets(). 3-!- String 8unctions <et us &irst consider t!e &unctions5 '!ic! are re@uired &or general string operations. T!e string &unctions are a*aila-le in t!e !eader &ile Xstring.!T. De can also 'rite t!ese oursel*es to understand t!eir 'or6ing. De can 'rite t!ese &unctions using Array o& /!aracters Pointers

3-!-1- String #engt) T!e lengt! o& t!e string is t!e nu$-er o& c!aracters in t!e string5 '!ic! includes spaces5 and all A./II c!aracters. As t!e array inde2 starts at ero5 'e can say t!e position occupied -y JU+E indicates t!e lengt! o& t!at string. <et us 'rite t!ese &unctions in t'o di&&erent 'ays $entioned earlier. 3-!-1-1- :sing Arra s int strlen1(c!ar s=>) L int iM+G '!ile(s=i> ZM JU+E) iOOG return(i)G P Here 'e incre$ent t!e positions till 'e reac! t!e end o& t!e string. T!e counter contains t!e si e o& t!e string.

3-!-1-2- :sing Pointers int strlen1(c!ar Rs) L c!ar RpG pMsG '!ile(Rs ZM JU+E) sOOG return(s3p)G PG T!e &unction is called in t!e sa$e $anner as earlier -ut in t!e &unction 'e accept t!e start address in s. T!is address is copied to p. T!e *aria-le s is incre$ented till 'e get end o& string. T!e di&&erence in t!e last and &irst address 'ill -e t!e lengt! o& t!e string. 3.5. .tring /opy C /opy s2 to s1 In t!is &unction 'e !a*e to copy t!e contents o& one string into anot!er string. 3.5.1. 7sing Arrays *oid strcopy(c!ar s1=>5 c!ar s2=>) L int iM+G '!ile( s2=i> ZM JU+E) s1=i> M s2=iOO>G s1=i>MEU+EG P Till it! c!aracter is not JU+E copy t!e c!aracter s and put a JU+E as t!e end o& t!e ne' string.

3.5.2. 7sing Pointers *oid strcopy( c!ar Rs15 c!ar Rs2)

L '!ile( Rs2) L Rs1 M Rs2G s1 OOG s2 OOG P Rs1 M Rs2G P 3.". .tring /o$pare 3.".1. 7sing Arrays *oid strco$p(c!ar s1=>5 c!ar s2=>) L int iM+G '!ile( s1=i> ZM JU+E :: s2=i> ZM JU+E) L i&(s1=i> ZM s2=i>) -rea6G else iOOG P return( s1=i> s2=i>)G P T!e &unction returns ero 5 i& t!e t'o strings are e@ual. D!en t!e &irst string is less co$pared to second5 it returns a negati*e *alue5 ot!er'ise a positi*e *alue. T!e reader can 'rite t!e sa$e &unction using t!e pointers.

3.%. /oncatenation o& .2 to t!e end o& .1 At t!e end o& string one add t!e string t'o. Bo till t!e end o& t!e &irst string. 4ro$ t!e ne2t position copy t!e c!aracters &ro$ t!e second string as long as t!ere are c!aracters in t!e second string and at t!e end close it 'it! a JU+E c!aracter. T!is is le&t as an e2ercise &or t!e student.

3.(. T'o Di$ensional Arrays De !a*e already seen !o' a t'o di$ensional array can -e represented in /5 in session 1. ;o' 'e can see !o' it is represented in t!e $e$ory. <i6e 'e !a*e a linear array 'it! single inde25 'e can also !a*e $ultidi$ensional arrays 'it! n inde2es. At present 'e 'ill discuss a-out t'o3di$ensional array5 1atri7T!ey are identi&ied 'it! t'o indices5 one is ro' inde2 and anot!er is t!e colu$n inde2. I& t!ere are 2 ro's and n colu$ns in t!e $atri2 'e say t!e $atri2 is o& t!e order (2 2 n)T!e pictorial representation isC " 1 2 3 " 1 2 ro3s 2%1 n co/u2ns fig 1- 1atri7 of si0e 2 7 n D!ile indicating t!e position (i59)5 i 'ill al'ays -e ro' and 9 'ill al'ays -e t!e colu$n nu$-er. T!e na$es i and 9 are not i$portant -ut t!eir position is al'ays *ery i$portant. De s!ould al'ays put t!e condition on t!e nu$-er o& *aria-les i.e. ro' nu$-er and colu$n nu$-er up to t!e $a2i$u$ ro' and colu$n nu$-er. T!is is *ery essential to a*oid undesira-le errors. As 'e !a*e already seen t!at t!e address arit!$etic ro' nu$-er 'ill start &ro$ " up to (2%1) and colu$n nu$-ers 'ill start &ro$ " to (n%1)Pos(2%19 n%1) n%2 n%1 Position(19n%1)

<et us see !o' t!ey are stored in t!e $e$ory. T!ey $ay -e stored ro'3'ise( ro' $a9or) or colu$n3'ise( colu$n $a9or). #ost o& t!e languages use ro' $a9or $et!od. T!is is re@uired -ecause $e$ory o& t!e co$puter is al'ays one3di$ensional. T!ere&ore &or a $atri2 a linear $e$ory o& si e (2 2 n) 'ill -e allocated. Hence in t!e &irst n locations 'e 'ill !a*e +t! ro'5 in t!e ne2t n location 'e 'ill !a*e 1st ro' and so on. +t! ro' 1st ro' $31t! ro'

+ 1 2 . . . . n31 n nO1. . . . 2n31. . . ($31)n . . . . $n31 (+5+)(+51). . .(+5n31). . . (15+)(151). . .(15n31). . . ($315+)($3151) . . .($315n31) fig 2- 2e2or representation of a t3o di2ensiona/ arra ;o' 'e can e*en &ind &ro$ t!e position (i59) 5 t!e actual location o& in t!e one3 di$ensional $e$ory. D!en 'e are in t!e it! ro'5 'e 6no' t!at (i31) ro's are -e&ore it and eac! !a*ing n $e$ory locations. T!ere&ore (i31)Rn $e$ory locations s!ould -e s6ipped to reac! it! ro'. It $ay appear to -e con&using as '!en 'e re&er to it! ro'5 t!e ro' nu$-er is actually (i31) and ( as our counting -egins at + rat!er t!an 1) !ence 1 st ro' 'ill -e ro' nu$-er + '!ic! $eans t!at t!e ro' nu$-er itsel& 'ill indicate as !o' $any ro's are co$plete prior to it. e.g. ,o' nu$-er 3 i.e. +5152535 is actually t!e 4t! ro' and t!ere&ore 3 ro's are co$pleted -e&ore 'e reac! it. Hence to reac! position (i59)5 'e s!ould s6ip (i R n) locations o& co$plete ro's and 9 locations &or &illed locations in t!at ro'. Hence t!e relati*e address 'ill -e ( iRnO9). (+5+)3W (+RnO+) 3W + (154)3W (1RnO4) 3W nO4 (552)3W (5RnO2) 3W 5nO2 _ etc. ($315n31)3W (($31)Rn O (n31)) 3W $n n O n O1 ;o' 'e $ay also -e re@uired to re*erse t!e 9o-5 i.e. i& 'e are gi*en a position in one3di$ensional $e$ory5 'e s!ould -e a-le to &ind ro' nu$-er and colu$n nu$-er. I&

p is t!e position5 t!en t!e ro' nu$-er 'ill -e ( p Q nO+) and t!e colu$n nu$-er 'ill -e ( p Y n). /onsider so$e -asic de&initions related to $atrices. 2. 3. 4. 4.1. 4.2. 4.3. #atri2 is said to -e s@uare i& nu$-er o& ro's is e@ual to t!e nu$-er o& colu$ns . i.e. 2AnD!en only t!e diagonal ele$ents o& t!e s@uare $atri2 are 15 and e*ery ot!er ele$ent is ero5 it is called as Identit 2atri7In a s@uare $atri25 position 'ise t!e ele$ents are di*ided as C Diagonal ele$ents <o'er triangle5 i.e. ele$ents -elo' t!e diagonal. 7pper triangle5 i.e. ele$ents a-o*e t!e diagonal.

Lower Triangle

Upper Triangle

Diagonal 8ig 3- t3o di2ensiona/ 2atri7 3it) c/assifications5. ,eading or re&erring to t!e ele$ents ro' 'ise. In t!is 'e 'ill re&er t!e ele$ents in a particular ro' one -y one5 i.e. ro' nu$-er re$ains sa$e in t!e process -ut t!e colu$n nu$-ers 'ill *ary. .i$ilarly 'e can also re&er to t!e ele$ents colu$n3'ise. Transpose o& t!e $atri2 is c!anging t!e ro' ele$ents to t!e colu$n ele$ents. i.e. t!e ele$ent in t!e (i59) position 'ill occupy (95i) position in t!e transpose. T!e transpose $atri2 'ill !a*e t!e si e n 2 $. .y$$etric $atri2 is a s@uare $atri2 '!ose transpose is identical to t!e original $atri2.

".

%.

.o$e &unctions you $ay use 'it! respect to $atrices C ,ead a $atri2 ro'3'iseQ colu$n3'ise.

2. D!en t!e nu$-er o& ro's and colu$ns are read outside t!e &unction . *oid read$at(int a=>=.II1>5 int $5 int n) L int i59G &or(iM+GiN$GiOO) &or(9M+G 9NnG 9OO) L print&(X 1nter ele$ents &or a=Yd>=Yd>MT5i59)G scan&(XYdT5:a=i>=9>)G P P 3. D!en t!e nu$-er o& ro's and colu$ns are read inside t!e &unction. .ince t!ese c!anges !a*e to -e re&lected -ac6 to calling &unction 'e use pointer *aria-les as argu$ents. 0oid read$at(int a=>=.II1>5 int R$5 int Rn) L int i59G print&(X 1nter t!e order o& t!e $atri2 X )G scan&(XYd YdT5$5n)G &or(iM+GiN R$GiOO) &or(9M+G 9N RnG9OO) L print&(X 1nter ele$ents &or a=Yd>=Yd>MT5i59)G scan&(XYdT5:a=i>=9>)G P

P Print t!e $atri2. 0oid print$at(int a=>=.II1>5 int $5 int n) L int i59G &or(iM+GiN$GiOO) L print&(X 1nter ele$ents &or a=Yd>=Yd>MT5i59)G print&(XYdT5a=i>=9>)G P P

4ind t!e su$ o& t!e upper triangle 5 diagonal and lo'er triangle $atri2 ele$ents.

int lo'$at(int a=>=.II1>5 int n) L int i595su$1M+G &or(iM+GiNnGiOO) &or(9M+G9NiG9OO) L su$1Msu$1Oa=i>=9>G P return(su$1)G P

T!e a-o*e &unction considers a s@uare $atri2 o& si e n . To &ind t!e su$ o& t!e upper triangle ele$ents 9ust interc!ange i and 9 in t!e state$ent su$1Msu$1Oa=i>=9> and $a6e it su$1Msu$1Oa=9>=i>. To &ind t!e su$ o& t!e diagonal ele$ents put a c!ec6 condition o& '!et!er it is e@ual to 9 -e&ore &inding t!e su$1. T!ese t'o &unctions are le&t to t!e students. /!ec6ing '!et!er a $atri2 is sy$$etric or not.

4or t!is5 t!e $atri2 !as to -e a s@uare $atri2 and t!e ele$ent at e*ery position (i59) $ust -e sa$e as t!at o& t!e ele$ent at t!e position (95i). Int sy$S$at(int a=>=.II1>5 int n) L int i59G &or(iM+GiNnGiOO) &or(9M+G9NiG9OO) L i&(a=i>=9> ZM a=9>=i>) return(+)G else return(1)G P P

Printing t!e transposeQ storing t!e transpose. To interc!ange it! ro' 'it! 9t! ro'5 'e s!ould s'ap( e2c!ange) t!e ele$ents in t!e colu$nsC *oid s'apSro'(int a=>=.II1>5int i5 int 95 int n)

L int 65te$pG &or(6M+G6NnG6OO) L te$p M a=i>=6>G a=i>=6>M a=9>=6>G a=9>=6>Mte$pG P P

3.). .parse #atri2 A matri$ in which ma-ority of the elements are +eroes they are #nown as Sparse matrices. Benerally in scienti&ic calculations5 a $atri2 'it! !undreds o& ro's and colu$ns $ay -e re@uired. T!e ele$ents re@uired could -e *ery &e' and re$aining positions are &illed 'it! eroes. 4or e2a$ple5 in a 1+ 2 1+ $atri25 only 15 ele$ents are non3 ero and t!e re$aining (5 locations contain eroes. In suc! cases 'e can store t!e $atri2 in a di&&erent &or$. T!e representation 'e 'ill -e using is a one3di$ensional array '!ere eac! data ite$ is re@uired to store t!ree t!ings. 1. ,o' nu$-er 2. /olu$n nu$-er 3. 0alue

Hence5 'e 'ill use a structure &or t!is case C struct sparse L int ro'5 col5 *alG Psp=.II1>G QR .II1 is declared as re@uired RQ

Here5 'e are declaring sp as one3di$ensional array o& structures. ;o' t!is array can represent a $atri2 !a*ing any nu$-er o& ro's and colu$ns -ut t!e only restriction is t!at t!e nu$-er o& non ero ele$ents s!ould not e2ceed .II1. e.g.

$atri2 A ,o'Q/ol + 1 2 3 4 1. 2 + + 33 + 2. + + 11 + + 3. + 3% + + 1 3 4 + + + +

&ig 4. $atri2 o& order 4 ] 5

.parse ,epresentationC

+ ro' col *al 4 5 %

1 + + 2

2 + 3 33

3 1 2 11

4 2 1 3%

5 2 4 1

" 3 + 34

% 3 4 )

&ig 5. sparse representation o& &ig 4. Here t!e position + in t!e sparse $atri2 representation actually in&or$s a-out t!e total nu$-er o& ro's 5 total nu$-er o& colu$ns and nu$-er o& non3 ero ele$ents. 4igure 5 s!o's as to !o' a particular $atri2 !as -een stored in ro's5 colu$ns and *al &or$. Here 'e s!ould pre&era-ly ta6e t!e ro' nu$-er in ascending $anner and &or eac! ro' 'e $ust ta6e t!e colu$ns in ascending $anner. T!is is not a rule -ut it !elps in a nu$-er o& applications. T!e ne2t @uestion is !o' to ta6e t!e input &ro$ t!e user. 8ne 'ay is to accept t!e &ull $atri2 and t!en con*erting it to t!e sparse &or$. T!e ot!er 'ay is to as6 t!e user to input t!e ro' nu$-er5 col nu$-er and *al. ;o' &or t!e &irst $et!od it is a si$ple $atri2 reading.

&or(iM+G iN$G iOO) &or(9M+G 9Nn G9OO) L scan&(XYdT5:a=i>=9>)G i&(a=i>=9> ZM +) L sp=6>.ro'MiG sp=6>.colM9G sp=6>.*alMa=i>=9>G 6OOG P P

=8,> ans M 1G do L scan&(XYd YdYdT5:sp=6>.ro'5:sp=6>.col5:sp=6>.*al)G 6OOG print&(X Un Any $ore *alues [ ( 1M Fes Q +M;o)T)G scan&(XYdT5:ans)G P'!ile(ansMM1)G Aot! t!ese operations 'ill 'or6 in an identical 'ay and 'ill generate sp array correctly. ;o' once t!e $atri2 is read properly5 t!e ne2t 9o- is to per&or$ operations li6e addition5 $ultiplication etc. Algorit!$ 1. To add t'o sparse $atrices5 e*ery ti$e 'e 'ill c!ec6 '!et!er ro' nu$-ers are sa$e. 2. I& not t!en copy t!e s$aller ro' *alue ele$ent into t!e resultant and incre$ent in t!at array. 3. 8t!er'ise c!ec6 t!e colu$n nu$-er5 i& t!ey are not sa$e5 t!en again copy t!e s$allest ele$ent into t!e resultant and incre$ent t!at array. 4. D!en t!e ro' nu$-ers and t!e colu$n nu$-ers are sa$e 5 'e 'ill add t!e ele$ents and store t!e$ into t!e resultant. T!e ad*antage o& t!e addition o& t!e t'o sparse $atrices is t!at irrespecti*e o& t!eir si e 'e can add t'o $atrices. De can understand t!is concept -y c!ec6ing t!e 'or6ing o& t!e &ollo'ing progra$.

K de&ine Nstdio.!W

K de&ine .II1 1+

QR ne' data type .P, 'it! t!ree ele$ents !as -een de&ined RQ typede& struct sparse L int ro'5col5*alG P .P,G QR t!is &unction reads t!e $atri2 in nor$al &or$ RQ *oid read$at(int a=>=.II1>5 int $5 int n) L int i59G &or(iM+G iN$G iOO) &or(9M+G 9Nn G9OO) scan&(XYdT5:a=i>=9>)G P

QR a &unction '!ic! con*erts t!e $atri2 into sparse &or$ RQ int $a6eSsparse( int a=>=.II1>5 int $5 int n5 .P, s1=>) L int i5956M1G &or(iM+G iN$G iOO) &or(9M+G 9Nn G9OO)

i&(a=i>=9> ZM +) L s1=6>.ro'MiG s1=6>.colM9G s1=6>.*alMa=i>=9>G 6OOG P s1=+>.ro'M$G QR &irst position contains RQ s1=+>.colMnG QR no o& ro's5 colu$ns and RQ s1=+>.*alM6G QR non3 ero ele$ents RQ return(6)G P

QR a &unction '!ic! displays sparse &or$ o& t!e $atri2 RQ displySspr(.P, s=>5 int n) L int iG print&(X ,o' Ut /ol Ut 0al UnT)G print&(X3333333333333333333333UnT)G &or(iM+GiNnGiOO) print&(XYdUtYdUtYdUnT5s=i>.ro'5s=i>.col5s=i>.*al)G P

QRRRRRRRRRR $ain() RRRRRRRRRQ $ain() L int a=.II1>=.II1>5 -=.II1>=.II1>5i59565$5n5i15i25n15n25i35n3G .P, s1=.II1>=.II1>5s2=.II1>=.II1>5 s3=.II1>=.II1> G i1Mi2Mi3M1G clrscr()G print&(X1nter t!e $atri2 ACUnT)G print&(X.i e o& $atri2 ACT)G scan&(XYd YdT5:$5:n)G print&(XPlease input t!e $atri2 ACUnT)G readS$at(a5$5n)G n1M $a6eSsparse(a5$5n5s1)G displaySspr(s15n1)G print&(X1nter t!e $atri2 ACUnT)G print&(X.i e o& $atri2 ACT)G scan&(XYd YdT5:$5:n)G print&(XPlease input t!e $atri2 ACUnT)G readS$at(-5$5n)G n2M $a6eSsparse(-5$5n5s2)G displaySspr(s25n2)G s3=+>.ro' M s1=+>.ro' W s2=+>.ro' [ s1=+>.ro' C s2=+>.ro'G s3=+>.col M s1=+>.col W s2=+>.col [ s1=+>.col C s2=+>.colG '!ile( i1 N n1 :: i2 N n2) QR till none o& t!e sparse RQ

L i&(s1=i1>.ro' MM s2=i2>.ro') L i&(s1=i1>.col MM s2=i2>.col) L

QR $atri2 ends Q

s3=i3>.ro'Ms1=i1>.ro'G QR '!en ro' and col RQ s3=i3>.colMs1=i1>.colG QR are sa$e copy t!e$ RQ s3=i3>.*al M s1=i1>.*al O s2=i2>.*alG QR add t!e$RQ i1OOG i2OOG i3OOG P else i&( s1=i1>.col N s2=i2>.col) L s3=i3>.ro'Ms1=i1>.ro'G s3=i3>.*al M s1=i1>.*alG i1OOG i3OOG QR '!en col.no o& &irst is less t!an t!eRQ QR col.no o& second copy t!e 1st ele$ent RQ P else L s3=i3>.ro'Ms2=i2>.ro'G s3=i3>.*al M s2=i2>.*alG i2OOG i3OOG s3=i3>.colMs2=i2>.colG s3=i3>.colMs1=i1>.colG

QR '!en col.no o& &irst is $ore t!an t!eRQ QR col.no o& second copy t!e 2nd ele$ent RQ P P else i&( s1=i1>.ro' N s2=i2>.ro') L s3=i3>.ro'Ms1=i1>.ro'G s3=i3>.*al M s1=i1>.*alG i1OOG i3OOG QR '!en ro'.no o& &irst is less t!an t!eRQ QR ro'.no o& second copy t!e 1st ele$ent RQ P else L s3=i3>.ro' M s2=i2>.ro'G s3=i3>.col M s2=i2>.colG s3=i3>.*al M s2=i2>.*alG i2OOG i3OOG QR '!en ro'.no o& &irst is $ore t!an t!eRQ QR ro'.no o& second copy t!e 2nd ele$ent RQ P P P '!ile( i2 N n2) s3=i3>.colMs1=i1>.colG

L s3=i3>.ro' M s2=i2>.ro'G s3=i3>.col M s2=i2>.colG s3=i3>.*al M s2=i2>.*alG i2OOG i3OOG QR '!en t!e &irst $atri2 ends RQ QR -ut t!e second does not t!en RQ QR copy t!e re$aining ele$ents o& RQ QR 2nd $atri2 RQ P '!ile( i1 N n1) L s3=i3>.ro' M s1=i1>.ro'G s3=i3>.col M s1=i1>.colG s3=i3>.*al M s1=i1>.*alG i1OOG i3OOG QR '!en t!e second $atri2 ends RQ QR -ut t!e &irst does not t!en RQ QR copy t!e re$aining ele$ents o& RQ QR &irst $atri2 RQ P n3 M i3G s3=o>.*alMn3G print&(XADD1D #AT,I] I. ...UnT)G displaySspr(s35n3)G P

8utputC 1nter t!e $atri2 AC .i e o& $atri2 AC 4 5 Please input t!e $atri2C 2 + + 33 + + + 4 + + + + " + ,o' 5 + + 1 1 2 3 + 31 5 + + + /ol 4 + 3 2 4 3 1 0al % 2 33 4 31 5 "

33333333333333

1nter t!e $atri2 AC .i e o& $atri2 AC 3 4 Please input t!e $atri2C 2 + + + 33 32 + +

+ + + 11 ,o' 4 + 1 1 2 /ol 3 + 1 2 3 0al 5 2 33 32 11

33333333333333

ADD1D #AT,I] I. . . . ,o' 5 + + 1 1 1 2 3 /ol 4 + 3 1 2 4 3 1 0al ( 4 33 33 2 31 1" " 33333333333333

3.1+. #ultiplication o& t!e sparse $atricesC ;o' let us consider a pro-le$ o& $ultiplying t'o sparse $atrices. It pro-a-le could -e *ery di&&icult as 'e do not e*en 6no' t!e si e o& t!e $atrices. .econdly5 t!e ot!er $atri25 to '!ic! t!e &irst $atri2 is going to -e $ultiplied s!ould satis&y t!e condition5 i.e. nu$-er o& colu$ns o& t!e &irst $atri2 $ust -e e@ual to t!e nu$-er o& ro's o& t!e second $atri2. In sparse $atri2 'e can al'ays add a ro' o& eroes or a colu$n o& eroes so t!at t!e si e -arrier doesnEt e2ist. Anot!er t!ing is t!at 'e s!ould ta6e transpose o& t!e second $atri2 or arrange it colu$n3'ise so t!at during $ultiplication5 instead o&

ro' o& t!e &irst into colu$n o& t!e second5 'e $ay !a*e ro'3to3ro' $ultiplication and t!e result 'ill -e t!e sa$e. 4irst 'e s!ould 'rite a &unction o& ta6ing t!e transpose o& t!e sparse $atri2. I& you loo6 at t!e de&inition o& t!e transpose5 '!ic! says t!at (i59) ele$ent in t!e original $atri2 'ill !a*e t!e position(95i) in transpose5 'e get t!e idea t!at 'e s!ould interc!ange t!e ro' nu$-er and t!e colu$n nu$-er. T!is can -e *ery easily done as gi*en -elo'C

&or(iM+G iN6G iOO) L te$p M sp=i>.ro'G sp=i>.ro' M sp=i>.colG sp=i>.col M te$pG P Aut t!en it 'onEt &ollo' t!e sorted nature o& t!e $atri25 i.e. ro' 'ise arrange$ent o& ele$ents. !ence5 'e 'ill !a*e to sort sp. ;o'5 t!e t'o $atrices 5 sp1 and sp25 are ready &or $ultiplication and t!e result is to -e stored in t!e $atri2 sp3. T!e pseudo code is gi*en -elo'. Fou $ay 'rite t!e progra$ and i$ple$ent it. 1. sp1 is &irst $atri2 and sp2 is t!e second $atri2 in t!e transpose &or$. 2. <et #1 and #2 -e nu$-er o& ele$ents in t!e $atrices sp1 and sp2. 3. i and 9 are positions o& sp1 and sp2 and 6 &or sp3. 4. iM+5 9M+5 6M+ 5. sp3=6>.ro' M i sp3=6>.col M 9 sp3=6>.*al M + ". i&(sp1=i>.col M sp2=9>.col) L sp3=6>.*al OM sp1=i>.-*al R sp2=9>.*alG

iOOG 9OOG P %. i&(sp1=i>.col N sp2=9>.col) iOOG else 9OOG (. i&((sp1=i>.ro' M sp3=6>.ro') :: ( sp2=9>.ro'Msp3=6>.ro')) goto step "G 7sing t!e a-o*e steps5 t!e user is ad*ised to 'rite a progra$ &or t!e $ultiplication o& t!e sparse $atrices.

3.11. #ultidi$ensional ArraysC De can !a*e t!ree di$ensional array or e*en $ore. T!e t!ree di$ensional arrays 'ill !a*e as usual t'o inde2es &or ro' nu$-er and colu$n nu$-er and t!e t!ird inde2 &or page nu$-er. /olu$n ,o'

Page

4ig ". #ultidi$ensional array De nor$ally read data page 'ise. T!is 'ill -e used only in case o& speci&ic applications '!ere all t!e data under consideration is related to eac! ot!er -y t!e position speci&ication. Ay t!ree di$ensional or $ore di$ensional array5 t!e p!ysical interpretation is rat!er di&&icult to i$agine. D!en 'e learn a-out ot!er data structures and a&ter considering t!e $e$ory re@uire$ent5 co$pared to t!e utili ation o& t!e $e$ory in $ultidi$ensional arrays5 'e $ay c!oose so$e ot!er data structure (*ery e&&ecti*e) related to t!e speci&ic application.

12ercisesC 1- Drite a progra$ to add an ele$ent into t!e array and delete an ele$ent &ro$ t!e array. 2- Drite a progra$ to add and $ultiply t'o $atrices in nor$al &or$. 3- Drite a progra$ to $ultiply t'o $atrices in .parse representation &or '!ic! t!e algorit!$ is gi*en in t!e c!apter. !- DAP ('rite a progra$ ) &or t!e transpose o& t!e sparse $atri2. 5- Discuss t!e li$itations and ad*antages o& t!e array as a data structure.

#in$ed #ists During this session you will learn about: 8. *in#ed allocation methods. 9. Singly lin#ed lists. :. 2asic operations on a singly lin#ed list. ;. Doubly lin#ed list. <. 2asic operations on a doubly lin#ed list. =>. Some applications of the lists. !-1- Introduction

De !a*e seen representation o& linear data structures -y using se@uential allocation $et!od o& storage5 as in5 arrays. Aut t!is is unaccepta-le in cases li6eC 4. 7npredicta-le storage re@uire$entsC T!e e2act a$ount o& data storage re@uired -y t!e progra$ *aries 'it! t!e a$ount o& data -eing processed. T!is $ay not -e a*aila-le at t!e ti$e 'e 'rite progra$s -ut are to -e deter$ined later. 4or e2a$ple5 lin6ed allocations are *ery -ene&icial in case o& polyno$ials. D!en 'e add t'o polyno$ials5 and none o& t!eir degrees $atc!5 t!e resulting polyno$ial !as t!e si e e@ual to t!e su$ o& t!e t'o polyno$ials to -e added. In suc! cases 'e can generate nodes (allocate $e$ory to t!e data $e$-er) '!ene*er re@uired5 i& 'e use lin6ed representation (dyna$ic $e$ory allocation). 5. 12tensi*e data $anipulation ta6es place. 4re@uently $any operations li6e insertion5 deletion etc5 are to -e per&or$ed on t!e lin6ed list. Pointers are used &or t!e dyna$ic $e$ory allocation. T!ese pointers are al'ays o& sa$e lengt! regardless o& '!ic! data ele$ent it is pointing to( int5 &loat5 struct etc5). T!is ena-les t!e $anipulation o& pointers to -e per&or$ed in a uni&or$ $anner using si$ple tec!ni@ues. T!ese $a6e us capa-le o& representing a $uc! $ore co$ple2 relations!ip -et'een t!e ele$ents o& a data structure t!an a linear order $et!od. T!e use o& pointers or lin6s to re&er to ele$ents o& a data structure i$plies t!at ele$ents5 '!ic! are logically ad9acent5 need not -e p!ysically ad9acent in t!e $e$ory. Vust li6e &a$ily $e$-ers dispersed5 -ut still -ound toget!er. !-2- Sing/ #in$ed #ist BorC ;ne 3a c)ain T!is is a list5 '!ic! can $ay consist o& an ordered set o& ele$ents t!at $ay *ary in nu$-er. 1ac! ele$ent in t!is lin6ed list is called as node. A node in a singly lin6ed list consists o& t'o parts5 a information part '!ere t!e actual data is stored and a lin# part5 '!ic! stores t!e address o& t!e successor(ne2t) node in t!e list. T!e order o& t!e ele$ents is $aintained -y t!is e2plicit lin6 -et'een t!e$. T!e typical node is as s!o'n C

Info

Link

?1D! 8ig 1- Structure of a >ode /onsider an e2a$ple '!ere t!e $ar6s o-tained -y t!e students are stored in a lin6ed list as s!o'n in t!e &igure C Hdata H;e2tH 333W 70 HN3;8D1 3WH fig 2- Sing/ #in$ed #ist In &igure 25 t!e arro's represent t!e lin6s. T!e data part o& eac! node consists o& t!e $ar6s o-tained -y a student and t!e ne7t part is a pointer to t!e ne2t node. T!e ;7<< in t!e last node indicates t!at t!is node is t!e last node in t!e list and !as no successors at present. In t!e a-o*e t!e e2a$ple t!e data part !as a single ele$ent $ar6s -ut you can !a*e as $any ele$ents as you re@uire5 li6e !is na$e5 class etc. T!ere are se*eral operations t!at 'e can per&or$ on lin6ed lists. De can see so$e o& t!e$ no'. To -egin 'it! 'e $ust de&ine a structure &or t!e node containing a data part and a lin6 part. De 'ill 'rite a progra$ to s!o' !o' to -uild a lin6ed list -y adding ne' nodes in t!e -eginning5 at t!e end or in t!e $iddle o& t!e lin6ed list. A &unction display() is used to display t!e contents o& t!e nodes present in t!e lin6ed list and a &unction delete()5 '!ic! can delete any node in t!e lin6ed list . 333W 333W 65
45 62 NULL

typede& struct node L int dataG struct node Rlin6G P;8D1G K include N stdio.! W K include N alloc.! W QR re@uired &or dyna$ic $e$ory RQ QR allocation RQ $ain() L ;8D1 RpG P M ;7<<G QR e$pty lin6ed list RQ

print&(XUn ;o o& ele$ents in t!e lin6ed list M YdT5 count(p))G append(:p51)G QR adds node at t!e end o& t!e list RQ append(:p52)G append(:p53)G append(:p54)G append(:p51%)G clrscr()G display(p)G addS-eg(:p5))))GQR adds node at t!e -eginning o& t!e list RQ addS-eg(:p5((()G addS-eg(:p5%%%)G display(p)G addSa&ter(p5%5+)G QR adds node a&ter speci&ied node RQ addSa&ter(p5251)G addSa&ter(p515)))G disply(p)G print&(XUn ;o o& ele$ents in t!e lin6ed list M YdT5 count(p))G delete(:p5((()G QR deletes t!e node speci&ied RQ delete(:p51)G delete(:p51+)G disply(p)G print&(XUn ;o o& ele$ents in t!e lin6ed list M YdT5 P To -egin 'it! t!e *aria-le p !as -een declared as pointer to a node. T!is pointer is a pointer to t!e &irst node in t!e list. ;o $atter !o' $any nodes get added to t!e list5 p 'ill al'ays -e t!e &irst node in t!e lin6ed list. D!en no node e2ists in t!e lin6ed list 5 p 'ill -e set to ;7<< to indicate t!at t!e lin6ed list is e$pty. ;o' 'e 'ill 'rite and discuss eac! o& t!ese &unctions. !-2-1-8unction to add a node at t)e end of t)e /in$ed /ist

append( ;8D1 RR@5 int nu$) L ;8D1 Rte$p5 RrG te$p M R@G i&( R@ MM ;7<<) QRlist e$pty5 create t!e &irst node RQ L te$p M $alloc(si eo&(;8D1))G te$p3Wdata M nu$G te$p3Wlin6 M ;7<<G R@ M te$pG P else L te$p M R@G '!ile(te$p3Wlin6 ZM ;7<< ) QR goto t!e end o& RQ te$p M te$p3Wlin6G QR list RQ r M $alloc(si eo&(;8D1))G r3Wdata M nu$G r3Wlin6 M ;7<<G te$p3Wlin6 M rG P P T!e append() &unction !as to deal 'it! t'o situationsC T!e node is -eing added to an e$pty list. T!e node is -eing added to t!e end o& t!e lin6ed list. QR add node at t!e RQ QR end o& t!e list RQ

In t!e &irst case5 t!e condition i&( R@ MM ;7<< ) gets satis&ied. Hence space is allocated &or t!e node using $alloc() . Data and t!e lin6 part o& t!is node are set up using t!e state$ents C te$p3Wdata M nu$G te$p3Wlin6 M ;7<<G

<astly p is $ade to point to t!is node5 since t!e &irst node !as -een added to t!e lin6ed list and p $ust al'ays point to t!e &irst node. ;ote t!at R@ is not!ing -ut e@ual to p. In t!e ot!er case5 '!en t!e lin6ed list is not e$pty5 t!e condition C i&( R@ MM ;7<<) 'ould &ail5 since R@ (i.e. p is non3;7<<). ;o' te$p is $ade to point to t!e &irst node in t!e lin6ed list t!roug! t!e state$ent5 te$p M R@G T!en using te$p 'e !a*e tra*ersed t!roug! t!e entire lin6ed list using t!e state$entsC '!ile(te$p3Wlin6 ZM ;7<<) te$pMte$p3Wlin6G T!e position o& t!e pointer -e&ore and a&ter tra*ersing t!e lin6ed list is s!o'n -elo'C

p te$p 333W 1 333W


2 333W

NULL

te$p

333W 1

333W

2 333W

NULL

node -eing added. 8ig 3- >ode 4eing added at t)e end of a S##

1ac! ti$e t!roug! t!e loop t!e state$ent te$pM te$p3Wlin6 $a6es te$p point to t!e ne2t node in t!e list. D!en te$p reac!es t!e last node t!e condition te$p3Wlin6 ZM ;7<< 'ould &ail. 8nce outside t!e loop 'e allocate t!e space &or t!e ne' node t!roug! t!e state$ent r M $alloc(si eo&(;8D1))G 8nce t!e space !as -een allocated &or t!e ne' node its data part is &illed 'it! nu$ and t!e lin6 part 'it! ;7<<. ;ote t!at t!is node is no' going to -e t!e last node in t!e list. All t!at no' re$ains is connecting t!e pre*ious last node to t!is ne' last node. T!e pre*ious node is -eing pointed to -y te$p and t!e ne' last node is -y r. t!ey are connected t!roug! t!e state$ent te$p3Wlin6 M rG T!ere is o&ten a con&usion a$ongst t!e -eginners as to !o' t!e state$ent te$pMte$p3Wlin6 $a6es te$p point to t!e ne2t node in t!e lin6ed list. <et us understand t!is 'it! t!e !elp o& an e2a$ple. .uppose in a lin6ed list containing 4 nodes te$p is pointing to t!e &irst node. T!is is s!o'n in t!e &igure -elo'C te$p 15+ 1 4++ 15+ 2 %++ 4++ 3 )1+ %++ 4 ;7<< )1+

8ig !- Actua/ representation of a S## in 2e2or Instead o& s!o'ing t!e lin6s to t!e ne2t node t!e a-o*e diagra$ s!o's t!e addresses o& t!e ne2t node in t!e lin6 part o& eac! node. D!en 'e e2ecute t!e state$ent te$p M te$p3W lin65 t!e rig!t !and side yields 4++. T!is address is no' stored in te$p. As a result5 te$p starts positioning nodes present at address 4++. In e&&ect t!e state$ent !as s!i&ted te$p so t!at it !as started positioning to t!e ne2t node in t!e lin6ed list. !-2-2- 8unction to add a node at t)e 4eginning of t)e /in$ed /ist addS-eg( ;8D1 RR@5 int nu$) L te$p M $alloc(si eo&(;8D1))G

te$p3Wdata M nu$G te$p3Wlin6 M R@G R@ M te$pG P .uppose t!ere are already 5 nodes in t!e list and 'e 'is! to add a ne' node at t!e -eginning o& t!is e2isting lin6ed list. T!is situation is s!o'n in t!e &igure -elo'. te$p p

1 333W 2 Defore Addition te$p p ))) 333W 1 333W

333W

333W

4 333W1% ;7<<

333W

333W

4 333W1% ;7<<

After Addition @ig 8. Addition of a node in the beginning of a S** 4or adding a ne' node at t!e -eginning5 &irstly space is allocated &or t!is node and data is stored in it t!roug! t!e state$ent te$p3Wdata M nu$G ;o' 'e need to $a6e t!e lin6 part o& t!is node point to t!e e2isting &irst node. T!is !as -een ac!ie*ed t!roug! t!e state$ent te$p3Wlin6 M R@G <astly t!is ne' node $ust -e $ade t!e &irst node in t!e list. T!is !as -een attained t!roug! t!e state$ent R@ M te$pG

A.7.6. @unction to add a node after the specified node addSa&ter(;8D1 R@5 int loc5 int nu$) L ;8D1 Rte$p5 RtG int iG te$p M @G &or( iM+ G iNlocG iOO) L te$p M te$p3Wlin6G i&(te$p MM ;7<<) L print&(X T!ere are less t!an Yd ele$ents in t!e listT5loc)G returnG P P r M $alloc(si eo&(;8D1))G r3Wdata M nu$G r3Wlin6 M te$p3Wlin6G te$p3Wlin6 M rG P T!e addSa&ter() &unction per$its us to add a ne' node a&ter a speci&ied nu$-er o& nodes in t!e lin6ed list. To -egin 'it!5 t!roug! a loop 'e s6ip t!e desired nu$-er o& nodes a&ter '!ic! a ne' node is to -e added. .uppose 'e 'is! to add a ne' node containing data as )) a&ter t!e t!ird node in t!e list. T!e position o& pointers once t!e control reac!es outside t!e for loop is s!o'n -elo'C P 1 333W 2 333W 3 te$p 333W r 4 333W1% ;7<<

99

Defore Insertion P 1 333W 2 333W 3 r


99

te$p 4 333W1% ;7<<

After Insertion 8ig '- Insertion of a node in t)e specified position T!e space is allocated &or t!e node to -e inserted and )) is stored in t!e data part o& it. All t!at re$ains to -e done is read9ust$ent o& lin6s suc! t!at )) goes in -et'een 3 and 4. t!is is ac!ie*ed troug! t!e state$ents r3Wlin6 M te$p3Wlin6G te$p3Wlin6 M rG T!e &irst state$ent $a6es lin6 part o& node containing )) to point to t!e node containg 4. t!e second state$ent ensures t!at t!e lin6 part o& t!e node containing 3 points to t!e ne' node. A.7.A. @unctions for display and count T!ese &unctions are *ery si$ple and straig!t&or'ard. .o no &urt!er e2planation is re@uired &or t!e$. QR &unction to count t!e nu$-er o& nodes in t!e lin6ed list RQ count(;8D1 R@) L int c M +G '!ile( @ ZM ;7<<) QR tra*erse t!e entire list RQ L

@ M @3Wlin6G cOOG P return (c)G P QR &unction to display t!e contents o& t!e lin6ed list RQ display(;8D1 R@) L print&(XUnT)G '!ile( @ ZM ;7<<) QR tra*erse t!e entire list RQ L print&(XYdT5@3Wdata)G @M@3Wlin6G P P

!-2-5- 8unction to de/ete t)e specified node fro2 t)e /ist delete(;8D1 RR@5 int nu$) L ;8D1 Rold5 Rte$pG te$p M R@G '!ile( te$p ZM ;7<<) L i&(te$p3Wdata MM nu$) L i&(te$p MM @) QRi& it is t!e &irst node RQ L R@ M te$p3Wlin6G &ree(te$p)G QR release t!e $e$ory RQ returnG P else L

old3Wlin6 MM te$p3Wlin6G &ree(te$p)G returnG P P else L old M te$pG te$pMte$p3Wlin6G P P print&(XUn 1le$ent Yd not &oundT5nu$)G P In t!is &unction t!roug! t!e 3)i/e loop 5 'e !a*e tra*ersed t!roug! t!e entire lin6ed list5 c!ec6ing at eac! node5 '!et!er it is t!e node to -e deleted. I& so5 'e !a*e c!ec6ed i& t!e node is t!e &irst node in t!e lin6ed list. I& it is so5 'e !a*e si$ply s!i&ted p to t!e ne2t node and t!en deleted t!e earlier node. I& t!e node to -e deleted is an inter$ediate node5 t!en t!e position o& *arious pointers and lin6s -e&ore and a&ter deletion are s!o'n -elo'.

P 1 333W 2

old 333W 3

te$p 333W 4 333W1% ;7<<

node to -e deleted M 4 Defore de/etion p old

1 333W 2 333W 3 333W 1% ;7<< te$p

4 gets deleted. T!is node

After de/etion 8ig 7- De/etion of a node fro2 S## T!oug! t!e a-o*e lin6ed list depicts a list o& integers5 a lin6ed list can -e used &or storing any si$ilar data. 4or e2a$ple5 'e can !a*e a lin6ed list o& &loats5 c!aracter array5 structure etc. A.6. Doubly *in#ed *ists BorC 0wo way chain In a singly lin6ed list 'e can tra*erse in only one direction (&or'ard)5 i.e. eac! node stores t!e address o& t!e ne2t node in t!e lin6ed list. It !as no 6no'ledge a-out '!ere t!e pre*ious node lies in t!e $e$ory. I& 'e are at t!e 12 t! node(say) and i& 'e 'ant to reac! 11t! node in t!e lin6ed list5 'e !a*e to tra*erse rig!t &ro$ t!e &irst node. T!is is a cu$-erso$e process. .o$e applications re@uire us to tra*erse in -ot! &or'ard and -ac6'ard directions. Here 'e can store in eac! node not only t!e address o& t!e ne2t node -ut also t!e address o& t!e pre*ious node in t!e lin6ed list. T!is arrange$ent is o&ten 6no'n as a Dou-ly lin6ed list . T!e node and t!e arrange$ent is s!o'n -elo'C

N33333333

I;48 P,10

333333333W ;1]T >;D6

8ig 8- >ode structure of a D## ;7<< 2+ 15 %+ "+ ;7<<

8ig +- Dou4/ #in$ed #ist T!e le&t pointer o& t!e le&t$ost node and t!e rig!t pointer o& t!e rig!t$ost node are ;7<< indicating t!e end in eac! direction. T!e &ollo'ing progra$ i$ple$ents t!e dou-ly lin6ed list. QR progra$ to $aintain a dou-ly lin6ed listRQ K include N alloc.! W typede& struct node L int dataG struct node Rpre*9 Ene2tG P;8D1G $ain() L ;8D1 RpG p M ;7<<G QR e$pty dou-ly lin6ed list RQ dSappend(:p511)G dSappend(:p521)G clrscr()G display(p)G print&(XUn ;o o& ele$ents in t!e dou-ly lin6ed list M YdT5 count(p))G dSaddS-eg(:p533)G dSaddS-eg(:p555)G disply(p)G print&(XUn ;o o& ele$ents in t!e dou-ly lin6ed list M YdT5 count(p))G dSaddSa&ter(p5154+++)G dSaddSa&ter(p525)+++)G

disply(p)G print&(XUn ;o o& ele$ents in t!e lin6ed list M YdT5 count(p))G dSdelete(:p551)G dSdelete(:p521)G disply(p)G print&(XUn ;o o& ele$ents in t!e lin6ed list M YdT5 P QR adds a ne' node at t!e -eginning o& t!e listRQ dSaddS-eg( ;8D1 RRs5 int nu$) L ;8D1 R@G QR create a ne' node RQ @ M $alloc(si eo&(;8D1))G QR assign data and pointersRQ @3Wpre* M ;7<<G @3Wdata M nu$G @3Wne2t M RsG QR $a6e t!e ne' node as !ead node RQ (Rs)3W pre* M @G Rs M @G P QR adds a ne' node at t!e end o& t!e dou-ly lin6ed listRQ dSappend( ;8D1 RRs5 int nu$) L ;8D1 Rr5 R@ MRsG i&( Rs MM ;7<<) QRlist e$pty5 create t!e &irst node RQ L Rs M $alloc(si eo&(;8D1))G ( Rs )3Wdata M nu$G ( Rs )3Wne2t M( Rs )3Wpre* M ;7<<G

P else L '!ile(@3Wne2t ZM ;7<< ) QR goto t!e end o& RQ @ M @3Wne2tG QR list RQ r M $alloc(si eo&(;8D1))G r3Wdata M nu$G r3Wne2t M ;7<<G r3Wpre* M @G @3Wne2t M rG P P QR adds a ne' node a&ter t!e speci&ied nu$-er o& nodes RQ dSaddSa&ter(;8D1 R@5 int loc5 int nu$) L ;8D1 Rte$pG int iG QR s6ip to t!e desired positionRQ &or( iM+ G iNlocG iOO) L @ M @3Wne2tG i&(@ MM ;7<<) L print&(X T!ere are less t!an Yd ele$ents in t!e listT5loc)G returnG P P QR insert a ne' node RQ @ M @3Wpre*G te$p M $alloc(si eo&(;8D1))G te$p3Wdata M nu$G te$p3Wpre* M @G te$p3Wne2t M @3Wne2tG QR add node at t!e RQ QR end o& t!e list RQ

te$p3Wne2t3Wpre* M te$pG @3Wne2t M te$pG P

QR counts t!e nu$-er o& nodes present in t!e lin6ed list RQ count(;8D1 R@) L int c M +G '!ile( @ ZM ;7<<) QR tra*erse t!e entire list RQ L @M@3Wne2tG cOOG P return (c)G P QR 4unction to display t!e contents o& t!e dou-ly lin6ed list RQ QR in le&t to rig!t order RQ display<,(;8D1 R@) L print&(XUnT)G '!ile( @ ZM ;7<<) QR tra*erse t!e entire list RQ L print&(XYdT5@3Wdata)G @M@3Wne2tG P P QR 4unction to display t!e contents o& t!e dou-ly lin6ed list RQ QR in rig!t to le&t order RQ display,<(;8D1 R@) L print&(XUnT)G

'!ile( @3Wne2t ZM ;7<<) QR tra*erse t!e entire list RQ L @M@3Wne2tG P '!ile( @ ZM ;7<<) L print&(XYdT5@3Wdata)G @M@3Wpre*G P P

QR to delete t!e speci&ied node &ro$ t!e list. RQ dSdelete(;8D1 RRs5 int nu$) L ;8D1 R@M RsG QR tra*erse t!e entire lin6ed list RQ '!ile( @ ZM ;7<<) L i&(@3Wdata MM nu$) L i&(@ MM Rs) QRi& it is t!e &irst node RQ L Rs M (Rs)3Wne2tG (Rs)3W pre* M ;7<<G P else L QR i& t!e node is last node RQ i&( @3Wne2t MM ;7<<) @3Wpre*3Wne2t M ;7<<G else QR node is inter$ediate RQ L @3Wpre*3Wne2t M @3Wne2tG @3Wne2t3Wpre* M @3Wpre*G

P &ree(@)G P returnG QR a&ter deletion RQ P @ M @3Wne2t G QR goto ne2t node i& not &ound RQ P print&(XUn 1le$ent Yd not &oundT5nu$)G P As you $ust !a*e reali ed -y no' any operation on lin6ed list in*ol*es ad9ust$ents o& lin6s. .ince 'e !a*e e2plained in detail a-out all t!e &unctions &or singly lin6ed list 5 it is not necessary to gi*e step3-y3step 'or6ing any$ore. De can understand t!e 'or6ing o& dou-ly lin6ed lists 'it! t!e !elp o& diagra$s. De !a*e s!o'n all t!e possi-le operations in a dou-ly lin6ed list along 'it! t!e &unctions used in diagra$s -elo'C Addition of new node to an empty lin#ed list /ase 1C Addition to an e$pty list ,elated &unction C dSappend()

p M Rs M ;7<< Defore Addition

P ;7<< 1 ;7<< ;e' node After Addition /ase 2C Addition to an e2isting lin6ed list ,elated &unction C dSappend()

; 1

99

Defore Appending P

; 1

99

After Appending

Addition of ne3 node at t)e 4eginning,elated 4unction C dSaddS-eg() p

; 1

33

2efore Addition @ p

33

After Addition

8ig 1"- Addition of nodes at various positions in t)e D##

/nsertion of a new node after a specified node ,elated &unction C dSaddSa&ter()

p @

te$p

66

;e' ;ode 2efore /nsertion P @ te$p

;1

66

After /nsertion 8ig 11- Insertion of node in t)e D## Deletion 1f a ?ode /ase 1C Deletion o& &irst node ,elated &unction C dSdelete() p @

; 55 ;ode to -e deleted C 55

Defore De/etion

p @

; 1

After Deletion /ase 2C Deletion o& t!e last node ,elated &unction C dSdelete() p @
88 N

; 1

;ode to -e deleted C (( Defore De/etion p @

; 1 After De/etion

/ase 3C Deletion o& t!e inter$ediate node ,elated &unction C dSdelete()

p ; 1
2

@
77 3 4 N

;ode to -e deleted C %% Defore De/etion p

; 1 After De/etion

8ig 11-De/etion of nodes fro2 various positions in t)e D## !-!. App/ications of t)e /in$ed /ists In co$puter science lin6ed lists are e2tensi*ely used in Data Aase #anage$ent .yste$s Process #anage$ent5 8perating .yste$s5 1ditors etc. 1arlier 'e sa' t!at !o' singly lin6ed list and dou-ly lin6ed list can -e i$ple$ented using t!e pointers. De also sa' t!at '!ile using arrays *ary o&ten t!e list o& ite$s to -e stored in an array is eit!er too s!ort or too -ig as co$pared to t!e declared si e o& t!e array. #oreo*er5 during progra$ e2ecution t!e list cannot gro' -eyond t!e si e o& t!e declared array. Also5 operations li6e insertions and deletions at a speci&ied location in a list re@uire a lot o& $o*e$ent o& data5 t!ere-y leading to an ine&&icient and ti$e3consu$ing algorit!$. T!e pri$ary ad*antage o& lin6ed list o*er an array is t!at t!e lin6ed list can gro' or s!rin6 in si e during its li&eti$e. In particular5 t!e lin6ed list Js $a2i$u$ si e need not -e 6no'n in ad*ance. In practical applications t!is o&ten $a6es it possi-le to !a*e se*eral data structures s!are t!e sa$e space5 'it!out paying particular attention to t!eir relati*e si e at any ti$e. T!e second ad*antage o& pro*iding &le2i-ility in allo'ing t!e ite$s to -e rearranged e&&iciently is gained at t!e e2pense o& @uic6 access to any ar-itrary ite$ in t!e list. In arrays 'e can access any ite$ at t!e sa$e ti$e as no tra*ersing is re@uired.

De are not suggesting t!at you s!ould not use arrays at all. T!ere are se*eral applications '!ere using arrays is $ore -ene&icial t!an using lin6ed lists. De $ust select a particular data structure depending on t!e re@uire$ents. <et us no' see so$e $ore applications o& t!e lin6ed lists5 li6e $erging t'o lists and !o' t!e lin6ed lists can -e used &or polyno$ial representations. 8unction to 1erge t)e t3o /ists#erge(;8D1 Rp5 ;8D1 R@5 ;8D1 RRs) L ;8D1 R G QR I& -ot! lists are e$pty RQ i&(pMM;7<< :: @ MM ;7<<) L returnG P QR tra*erse -ot! lin6ed lists till t!e end. I& end o& any one lin6ed list is encountered t!en t!e loop is ter$inated RQ '!ile( p ZM ;7<< :: @ ZM ;7<<) L QR i& node -eing added in t!e &irst list RQ i& ( Rs MM ;7<<) L Rs M $alloc(si eo&(;8D1))G M RsG P else L 3Wlin6 M $alloc(si eo&(;8D1))G M 3Wlin6G P i&( p3Wdata N @3Wdata) L 3Wdata M p3WdataG p M p3Wlin6G P else

L i&( p3Wdata W @3Wdata) L 3Wdata M @3WdataG @ M @3Wlin6G P else L i&( p3Wdata MM @3Wdata) L 3Wdata M @3WdataG @ M @3Wlin6G p M p3Wlin6G P P P P QR i& end o& &irst list !as not -een reac!ed RQ '!ile( p ZM ;7<<) L 3Wlin6 M $alloc(si eo&(;8D1))G M 3Wlin6G 3Wdata M p3WdataG p M p3Wlin6G P QR i& end o& second list !as not -een reac!ed RQ '!ile( @ ZM ;7<<) L 3Wlin6 M $alloc(si eo&(;8D1))G M 3Wlin6G 3Wdata M @3WdataG @ M @3Wlin6G P 3Wlin6 M ;7<<G P In t!is progra$5 assu$e t!at structure ;8D1 'it! data and lin6 is a*aila-le. Also using add() used &or singly lin6ed list earlier 'e !a*e t'o lin6ed lists. T!ree pointers point to t!ree lin6ed lists. T!e $erge &unction can -e called to $erge t!e t'o lin6ed lists.

T!is $erged list is pointed to -y t!e pointer t!ird. D!ile $erging t'o lists it is assu$ed t!at t!e lists t!e$sel*es are in ascending order. !-5- #in$ed /ists and Po/ no2ia/sPolyno$ials can -e $aintained using a lin6ed list. To !a*e a polyno$ial li6e 524 S 223 O %22 O 1+2 ( 5 eac! node s!ould consist o& t!ree ele$ents5 na$ely coe&&icient5 e2ponent and a lin6 to t!e ne2t ite$. D!ile $aintaining t!e polyno$ial it is assu$ed t!at t!e e2ponent o& eac! successi*e ter$ is less t!an t!at o& t!e pre*ious ter$. I& t!is is not t!e case you can also use a &unction to -uild a list5 '!ic! $aintains t!is order. 8nce 'e -uild a lin6ed list to represent t!e polyno$ial 'e can per&or$ operations li6e addition and $ultiplication. /onsider t!e progra$ gi*en -elo'. QR progra$ to add t'o polyno$ials RQ typede& struct node L &loat coe&&G int e2pG struct node Rlin6G PP;8D1G *oid pSappend(P;8D1 RR5 &loat5 int)G *oid pSaddition(P;8D1 R5 P;8D1 R5 P;8D1 RR)G $ain() L P;8D1 (&irst5 Rsecond5 RtotalG int i M +G &irst M second M total M ;7<<GQR e$pty lin6ed lists RQ pSappend(:&irst515455)G pSappend(:&irst515554)G pSappend(:&irst515%52)G pSappend(:&irst515(51)G pSappend(:&irst515)5+)G clrscr()G displaySp(&irst)G pSappend(:second51555")G pSappend(:second525555)G

pSappend(:second5335554)G pSappend(:second545553)G pSappend(:second5"5551)G displaySp(second)G pSaddition(&irst5second5 :total) displaySp(total)G PG T!e &unction to append t!e polyno$ial pSappend() and displaySp() are si$ilar to our &unctions &or singly lin6ed list. .o t!ey are e2pected to -e 'ritten -y t!e user. T!e &unction to add t'o polyno$ials is gi*en -elo'. *oid pSaddition(P;8D1 R25 P;8D1 Ry5 P;8D1 RRs) L P;8D1 R G QR i& -ot! lists are e$pty RQ i&( 2 MM ;7<< :: y MM ;7<< ) returnG QR tra*erse till one node ends RQ '!ile( 2 ZM ;7<< :: y ZM ;7<< ) L i& ( Rs MM ;7<<) L Rs M $alloc(si eo&(P;8D1))G M RsG P else L 3Wlin6 M $alloc(si eo&(P;8D1))G M 3Wlin6G P QR store a ter$ o& larger degree i& polyno$ial RQ i&( 23We2p N y3We2p) L 3Wcoe&& M y3Wcoe&&G

3We2p M y3We2pG y M y3Wlin6G QR goto t!e ne2t node RQ P else L i&( 23We2p W y3We2p) L 3Wcoe&& M 23Wcoe&&G 23We2p M 23We2pG 2 M 23Wlin6G QR goto t!e ne2t node RQ P else L i&( 23We2p MM y3We2p) L 3Wcoe&& M 23Wcoe&& O y3Wcoe&&G 23We2p M 23We2pG 2 M 23Wlin6G QR goto t!e ne2t node RQ y M y3Wlin6G QR goto t!e ne2t node RQ P P P P QRassign re$aining ele$ents o& t!e &irst polyno$ial to t!e result RQ '!ile( 2 ZM ;7<<) L i&( Rs MM ;7<<) L Rs M $alloc(si eo&(P;8D1))G M RsG P else L 3Wlin6 M $alloc(si eo&(P;8D1))G M 3Wlin6G P 3Wcoe& M 23Wcoe&G 3We2p M 23We2pG 2 M 23Wlin6G P

QRassign re$aining ele$ents o& t!e second polyno$ial to t!e result RQ '!ile( y ZM ;7<<) L i&( Rs MM ;7<<) L Rs M $alloc(si eo&(P;8D1))G M RsG P else L 3Wlin6 M $alloc(si eo&(P;8D1))G M 3Wlin6G P 3Wcoe& M y3Wcoe&G 3We2p M y3We2pG y M y3Wlin6G P 3Wlin6 M ;7<<G QR at t!e end o& list append ;7<<RQ P In t!is progra$ t'o polyno$ials are -uilt and pointed -y t!e pointers &irst and second. ;e2t t!e &unction pSaddition() is called to carry out t!e addition o& t!ese t'o polyno$ials. In t!is &unction t!e lin6ed lists representing t!e t'o polyno$ials are tra*ersed till t!e end o& one o& t!e$ is reac!ed. D!ile doing t!is tra*ersal t!e polyno$ials are co$pared on ter$3-y3ter$ -asis. I& t!e e2ponents o& t!e t'o ter$s -eing co$pared are e@ual t!en t!eir coe&&icients re added and t!e result is stored in t!e t!ird polyno$ial. I& t!e e2ponents are not e@ual t!en t!e -igger e2ponent is added to t!e t!ird polyno$ial. During t!e tra*ersal i& t!e end o& one list is reac!ed t!e control -rea6s out o& t!e '!ile loop. ;o' t!e re$aining ter$s o& t!at polyno$ial are si$ply appended to t!e resulting polyno$ial. <astly t!e result is displayed. 67ercises? 1. DAP &or adding and deleting nodes &ro$ an ascending order lin6ed list. 2. DAP to re*erse a singly lin6ed list -y ad9usting t!e lin6s. 3. Drite progra$s &or re*ersing a dou-ly lin6ed list (t!oug! it does not ser*e any purpose it 'ill gi*e practice to $anipulate t!e pointers. 4. DAP to delete a node a&ter t!e speci&ied node and -e&ore a speci&ied node using -ot! singly and dou-ly lin6ed lists.

5. ". %. (.

DAP to -rea6 a lin6ed list into t'o lin6ed lists using -ot! .<< and D<<. Drite a progra$ to add t'o polyno$ials using a D<<. DAP to $ultiply t'o polyno$ials &or -ot! .<< and D<<. DAP to add t'o long integers. 1ac! integer $ay contain 15 to 2+ digits5 '!ic! can -e stored in nodes5 a digit eac! or $ore depending on t!e users c!oice. Add t!ese long integers (&ro$ least signi&icant digit -ac6'ards) and display t!e resultant list.

Session ' (rap)s During this session you will learn about: 1. 2. 3. 4. Draphs. Ad-acency matri$ and lists. 2readth search and depth search on graphs. Some important functions and definitions regarding graphs.

'-1. Introduction A graph is a collection of vertices and edges, D EFG, !H where G is set of vertices and ! is set of edges. An edge is defined as pair of vertices, which are ad-acent to each other. D!en t!ese pairs are ordered5 t!e grap! is 6no'n as directed graph. T!ese grap!s !a*e $any properties and t!ey are *ery i$portant -ecause t!ey actually represent $any practical situations5 li6e net'or6s. In our current discussion 'e are interested on t!e algorit!$s '!ic! 'ill -e used &or $ost o& t!e pro-le$s related to grap!s li6e to c!ec6 connecti*ity5 t!e dept! &irst searc! and -readt! &irst searc!5 to &ind a pat! &ro$ one *erte2 to anot!er5 to &ind $ultiple pat!s &ro$ one *erte2 to anot!er5 to &ind t!e nu$-er o& co$ponents o& t!e grap!5 to &ind t!e critical *ertices and edges. T!e -asic pro-le$ a-out t!e grap! is its representation &or progra$$ing.

'-2- Ad<acenc 1atri7 and Ad<acenc /ists De can use t!e ad9acency $atri25 i.e. a $atri2 '!ose ro's and colu$ns -ot! represent t!e *ertices to represent grap!s. In suc! a $atri2 '!en t!e it! ro'5 9t! colu$n ele$ent is 15 'e say t!at t!ere is an edge -et'een t!e i t! and 9t! *erte2. D!en t!ere is no edge t!e *alue 'ill -e ero. T!e ot!er representation is to prepare t!e ad9acency lists &or eac! *erte2. ;o' 'e 'ill see an e2a$ple o& a grap! and see !o' an ad9acency $atri2 can -e 'ritten &or it. De 'ill also see t!e ad9acency relations e2pressed in &or$ o& a lin6ed list. 4or 12a$pleC

8ig 1 (rap) T!e ad9acency $atri2 &or representing t!is grap! isC 01 01 02 03 + 1 + 02 1 + + 03 + + + 04 + 1 1 05 1 1 1 0" 1 + + 0% + + + 0( + + 1

04 05 0" 0% 0(

+ 1 1 + +

1 1 + + +

1 1 + + 1

+ + + + +

+ + 1 1 1

+ 1 + + +

+ 1 + + +

+ 1 + + +

8ig 2- Ad<acenc 1atri7 representation of grap) in fig 1 Ad9acency list 'ill -eC 01 3W 02 3W 05 3W 0" 02 3W 01 3W 04 3W 05 03 3W 04 3W 05 3W 0( 04 3W 02 3W 03 05 3W 01 3W 02 3W 03 3W 0" 3W 0% 3W 0( 0" 3W 01 3W 05 0% 3W 05 0( 3W 03 3W 05 8ig 3- Ad<acenc #ist representation of grap) in fig 1 '-3- Dreadt) first searc) and Dept) first searc) .uppose t!e grap! is represented as an ad9acency $atri25 and 'e are re@uired to !a*e t!e -readt! &irst searc! o& t!e grap!. Here 'e 'ill re@uire t!e starting *erte2 &ro$ '!ic! t!is searc! 'ill -egin. 4irst t!at *erte2 'ill -e printed5 t!en all t!e *ertices5 '!ic! are ad9acent to it5 are printed and so on. I& 'e !a*e a $atri2 and t!ere are n *ertices. <et t!e starting *erte2 -e 9. ;o' t!e 9t! *erte2 'ill -e printed &irst5 and to &ind all t!e *ertices ad9acent to t!is *erte25 'e $ust tra*el along 9t! ro' o& t!e $atri25 and '!ene*er 'e &ind 1 'e 'ill print t!e corresponding colu$n nu$-er. ;e2t ti$e 'e 'ill re@uire eac! o& t!e *ertices printed recently so t!at 'e can tra*el le*el -y le*el. 4or t!e sa$e purpose 'e 'ill pus! into a @ueue all t!e colu$ns 'it! t!e *alue one in t!e 9t! ro'. ;e2t ti$e pop t!e *erte2 nu$-er &ro$ t!e @ueue and print it. ,eplace t!e *alue o& 95 '!ic! is currently printed. Again pus! all t!e *ertices t!at are ad9acent to t!is *erte2 into t!e @ueue and continue t!e a-o*e process until all t!e *ertices are dealt 'it!.

,e$e$-er t!ere 'ill -e $any *ertices5 '!ic! 'ill -e connected to $ore t!an a *erte25 and t!ere&ore t!ere are c!ances t!at 'e $ay repeat so$e o& t!e *ertices or t!ere 'ill -e an in&inite loop. To a*oid t!is pro-le$5 'e use '!at is 6no'n as *isited array. It 'ill -e initially all eroes. D!ene*er a *erte2 is pus!ed into t!e @ueue t!e corresponding position t!e *isited array is c!anged to 1. ;o' 'e use anot!er rule t!at 'e pus! only t!ose *ertices into t!e @ueue '!ose corresponding *alue in t!e *isited array at t!at point is ero. D!en all t!e *ertices are printed 'e 'ill stop. .o$eti$es it !appens t!at a particular *erte2 or a group o& *ertices is non reac!a-le &ro$ t!e current *erte2 and in t!is case t!e grap! is Jnot connected). 0herefore a connected graph is the one in which we can travel through all the vertices starting from a current node. Algorit!$ &or t!e -readt! &irst tra*ersal in a grap!C Initiali e t!e ad9acency $atri2 p to all eroes. Accept t!e nu$-er o& *ertices &ro$ t!e user5 say n. Initiali e t!e *isited array * to all eroes. Accept t!e grap!. a. Initiali e i to +. -. Accept t!e *erte2 ad9acent to it! *erte25 say 9. c. #a6e p=i>=9> M p=9>=i> M 15 as t!ey are ad9acent to eac! ot!er. d. I& $ore *ertices are ad9acent to it! *erte2 t!en goto step (a). e. ;o' consider t!e ne2t *erte2 i.e. incre$ent i and repeat &ro$ step(a). 9. Accept t!e starting *erte2 say i. 10.Pus! i to t!e @ueue5 and $ar6 it as *isited5 i.e. *=i>M1. 11.Pop a *erte2 &ro$ @ueue5 say i. 12.Print i. 13..earc! in it! ro' &or 15 5. 6. 7. 8. &. Initiali e 9 to +. g. I& t!e 9t! *erte2 is ad9acent to i and not *isited i.e. I&(p=i>=9>MM1 :: *=i> ZM 1)5 pus! 9 to t!e @ueue and $ar6 it as *isited5 i.e. *=9>M1. !. Incre$ent 9 and i& t!e nu$-er o& *ertices is not o*er t!en repeat &ro$ step(-). 14. I& @ueue is not e$pty repeat &ro$ step %. 15. ;o' c!ec6 '!et!er all *ertices are *isited. i. Initiali e 9M+ and &lag M 31. 9. I& 9t! *erte2 is not *isited5 set &lag to 9. 6. Incre$ent 95 and i& nu$-er o& *ertices is not o*er5 repeat &ro$ step -.

16. I& &lag ZM 315 t!e grap! is not a connected grap!. 8t!er'ise it is a connected grap!. 17. .top. T!e algorit!$ 'ill gi*e us a clear idea a-out connectedness o& t!e grap!. Here 'e are accepting t!e grap! as t!e ad9acency list. T!e a-o*e algorit!$ can -e c!anged &or t!e lin6ed lists as -elo'. 18.Accept t!e nu$-er o& *ertices &ro$ t!e user 5 say n. 19./reate a list !a*ing n nodes. T!is list is called as a !eader list. It 'ill -e connected -y t!e do'n pointer '!ere as t!e ad9acency list 'ill -e connected -y t!e ne2t pointer. ,e$e$-er t!at t!ese t'o lists 'ill &ollo' di&&erent structures. 20.Initiali e t!e *isited array * to eroes. 21.Accept t!e grap!. l. Accept an edge say i59. $. .earc! in t!e !eader list &or *erte2 i5 and in t!e ad9acency list o& t!at *erte2 i5 attac! a node o& *erte2 9. n. .earc! in t!e !eader list &or *erte2 95 and in t!e ad9acency list o& t!at *erte2 95 attac! a node o& *erte2 i. o. I& $ore edges t!en goto step (a). 22.Accept t!e starting *erte2 say i. 23.Pus! i to t!e @ueue5 and $ar6 it as *isited5 i.e. *=i>M1. 24.Pop a *erte2 &ro$ @ueue5 say i. 25.Print i. 26.#o*e in t!e ad9acency list o& it! *erte25 and &or e*ery node say 9 '!ic! is not *isited5 pus! it to t!e @ueue and $ar6 it as *isited5 i.e. *=9>M1. 27.I& @ueue is not e$pty repeat &ro$ step %. 28. ;o' c!ec6 '!et!er all *ertices are *isited. a. Initiali e 9M+ and &lag M 31. -. I& 9t! *erte2 is not *isited5 set &lag to 9. c. Incre$ent 95 and i& nu$-er o& *ertices is not o*er5 repeat &ro$ step -. 29. I& &lag ZM 315 t!e grap! is not a connected grap!. 8t!er'ise it is a connected grap!. 30. .top. @or depth first search, the algorithm is same as breadth first but in place of "ueues we have to use stac#s. /onsider t!e &ollo'ing grap!5

8ig !- (rap) T!e ad9acency $atri2 'ill -e + + 1 2 3 4 5 " + 1 + 1 + + + 1 1 + 1 1 + + + 2 + 1 + + 1 1 + 3 1 1 + + + + 1 4 + 1 1 + + 1 1 5 + + 1 + 1 + 1 " + + + 1 1 1 +

8ig 5- Ad<acenc 1atri7 representation of grap) in fig ! T!e ad9acency list 'ill -eC ] M ;7<<

8ig '- Ad<acenc #ist representation of grap) in fig ! T!e &igure 5 s!o's !o' t!e grap! is stored using t!e $atrices and &igure " s!o's it stored as ad9acency list. T!e logic o& -ot! t!e algorit!$s re$ain sa$e -ut t!e c!ange in representation is due to t!e data structure t!at 'e are using. T!e data structure 'ill al'ays pro*ide so$e additional &eatures and &acilities applica-le to a particular pro-le$. D!en 'e try to utili e t!ese &acilities t!e algorit!$ is -ound to c!ange. 8-ser*e t!at in t!e a-o*e t'o cases '!en 'e are using t!e arrays5 'e !a*e a si$ple representation -ut once t!e grap! is inputted5 to c!ec6 t!e ad9acency 'e !a*e to c!ec6 again '!et!er a particular position contains a ero or one. T!is c!ec6 is not re@uired !en 'e are using t!e lin6ed list. Here t!e *ertices '!ic! are ad9acent to a particular *erte2 are a*aila-le directly and can -e used 'it!out any c!ec6s. D!ile creating t!e ad9acency list5 o-ser*e t!at 'e are re@uired to c!ec6 &or t!e appropriate position in t!e !eader list and t!en only 'e can insert t!e node. In case o& arrays 'e si$ply place t!e ele$ents in t!e it! ro' and 9t! colu$n5 t!ere is no c!ec6 in*ol*ed in t!e process. In -ot! t!e $et!ods5 'e !a*e used t!e sa$e array *isited. T!is is -ecause5 'e are assu$ing t!at t!e *ertices are gi*en nu$-ers and not na$es. I& 'e use na$es to re&er *ertices t!en 'e need a lin6ed list to store t!e status o& *ertices. Here -e&ore inserting any *erte2 into t!e @ueue t!e '!ole *isited list !as to -e scanned5 as t!ere is no direct 'ay o& getting t!e in&or$ation t!at '!et!er a particular *erte2 is *isited. As stated earlier5 o-ser*e t!at t!e !eader list as 'ell as t!e ad9acency lists !a*e di&&erent structures. T!ese structures are gi*en -elo'C struct ad9Snode

L int *erG struct ad9Snode Rne2tG P struct !eadSnode L int *erG struct !eadSnode Rdo'nG struct ad9Snode Rne2tG P In t!e creation o& t!e lists 'e &ind t!at 'e are re@uired to !a*e c!ec6s &or searc!ing t!e *erte2 in t!e !ead list. Do not !a*e t!e $isconception as t!e !eadlist 'ill contain all t!e nodes in a sorted &as!ion. T!e !eadlist 'ill also get created si$ultaneously. D!ene*er a ne' *erte2 is recei*ed5 it 'ill -e inserted in t!e !ead list. Here 'e are re@uired to 6eep trac6 o& t!e additions as 'ell as searc! and tra*ersals in -ot! t!e types o& t!e lists. .o$eti$es a co$-ination o& data structures 'ill gi*e us a -etter algorit!$ suita-le &or t!e current application. In &act 'e s!ould !a*e array &or !eader nodes and not t!e list. Ay t!is 'e can reduce t!e initial searc!ing ti$e and directly go to a particular ad9acency list. T!e &ollo'ing progra$ 'ill read t!e grap!5 gi*en -y t!e user in t!e &or$ o& edges. A proper list is &or$ed as s!o'n in t!e pre*ious &igure. T!e ai$ o& t!e progra$ is to print t!e -readt! &irst and dept! &irst searc! o& t!e gi*en grap!. T!e logic is i$ple$ented -y t!e use o& stac6 or @ueue5 '!ic! are in turn i$ple$ented using5 lin6ed lists. T!is progra$ can also -e considered as a good e2a$ple &or !andling o& t!e $ultiple lists. Here 'e are !andling t!e ad9acency list corresponding to all t!e *ertices. D!ile 'riting t!e co$plete progra$ you are e2pected to 'rite t!e &ollo'ing &unctions yoursel&. T!e &unctions use lin6ed list representation &or @ueues and stac6s. 1. 4unction to create t!e @ueue. ? create()G 2. 4unction To insert an ele$ent into t!e @ueue. *oid pus!1 (c!ar data5 ? !ead)G 3. 4unction To delete an ele$ent &ro$ t!e @ueue.

c!ar pop1 ( ? !ead)G ". 4unction to c!ec6 '!et!er t!e @ueue is e$pty. int @Se$pty(? !ead)G %. 4unction to create a stac6. .T\ createst()G (. 4unction to c!ec6 '!et!er t!e stac6 is e$pty. int st6Se$pty(.T\ !ead)G ). 4unction To pus! an ele$ent into t!e stac6. *oid pus!(c!ar data5 .T\ !)G 1+.4unction To pop an ele$ent &ro$ t!e stac6. c!ar pop ( .T\ !)G QR T!e grap! representation starts !ere RQ typede& struct *erlist L c!ar *erte2G struct *erlist Rrig!tG PR0,G typede& struct !list L int &lag c!ar *erte2G struct *erlist Rrig!tG struct !list Rdo'nG PR0HG 0H create1() L 0H !eaderG !eader M $alloc(si eo&(struct !list))G !eader3Wdo'n M !eader 3Wrig!t M ;7<<G return(!eader)G P QR &unction to &ind t!e *erte2 c5 in t!e !eader list RQ

QR &or ad9acency list RQ

QR t!e list o& all *ertices RQ

0H &ind(c!ar c5 0H !eader) L 0H tt$pG tt$p M !eaderG do L i&(tte$p3W*erte2 MM c) return tt$pG QR returns pointer to t!e !eader node RQ else tt$pM tt$p3Wdo'nG P'!ile (tt$p)G return(tt$p)G QR returns ;7<<5 '!en a-sent RQ P 0, getS*er(c!ar c2) L 0, ne'1G ne'1 M $alloc(si eo&(struct *erlist))G ne'13W*erte2Mc2G QR generating a node &or ad9. <ist RQ ne'13Wrig!t M ;7<<G return(ne'1)G P 0H getSc!(c!ar c) L 0H ne'2G ne'2 M $alloc(si eo&(struct !list))G ne'23W*erte2 M cG QR generating a node &or !eader <ist RQ ne'23Wrig!t M ;7<<G ne'23Wdo'n M ;7<<G ne'23W&lag M +G return(ne'2)G P QR &unction to display t!e ad9acency list RQ

*oid display(/H !eader) L 0H tt$pG 0, tG tt$p M !eader 3W do'nG '!ile(tt$p) L print&(XYc MMW X5 tt$p3W*erte2)G tM tt$p3Wrig!tG '!ile(t) L print&(XYc`Tt3W*erte2)G t M t3Wrig!t)G P print&(X;7<<UnT)G tt$p M tt$p3Wdo'nG P P *oid searc!(c!ar c15 c!ar c25 0H !eader) L 0H tt$p5 ne'1G 0, ne'2G tt$p M !eaderG '!ile(tt$p3Wdo'n ZM ;7<< :: tt$p3Wdo'n3W*erte2 ZM c1) tt$p M tt$p3Wdo'nG QRsearc! node c1 in t!e !eader list RQ i&(tt$p3Wdo'n3W*erte2 MM c1) L ne'2 M getS*er(c2)G QR generate a node &or c2 and add to t!e list RQ ne'23Wrig!t M tt$p3Wdo'n3Wrig!tG tt$p3Wdo'n3Wrig!t M n'e2G P else L ne'1 M getS*!(c1)G QR i& !eader list does not contain node &or c1 RQ

ne'13Wdo'n M tt$p3Wdo'nG tt$p3Wdo'n M ne'1G ne'13W&lag M +G tt$pMne'1G ne'2MgetS*er(c2)G ne'23Wrig!t M tt$p3Wrig!tG tt$p3Wrig!tMne'2G P P

QR &unction &or A,1ADTH 4I,.T .1A,/H RQ *oid -&s(0H !eader) L c!ar c15 ans=3+>G int 6M+5 iM+G 0, tG 0H tt$pG ? !ead15 !!G !ead1 M create()G tt$p M !eader3Wdo'nG '!ile(tt$p) L tt$p3W&lag M +G tt$p M tt$p3Wdo'nG P tt$p M !eader3Wdo'nG print&(X1nter t!e c!aracter you 'ant to start &ro$UnT)G &lus!all()G c1Mgetc!ar()G do L tt$p M &ind(c15!eader)G print&(XYcUnT5 tt$p3W*erte2)G ans=iOO>M tt$p3W*erte2G

tt$p3W&lag M 1G t M tt$p3Wrig!tG '!ile(t) L tt$pM &ind(t3W*erte25 !eader)G i&(tt$p3W&lag MM +) L pus!1(t3W*erte25 !ead1)G print&(XUn Yc *erte2 is pus!ed in t!e @ueue UnT5 t3W*erte2)G tt$p3W&lag M 1G getc!()G P t M t3W rig!tG P print&(X no' t!e @ueue is _UnT)G !!M !ead13Wne2tG print&(X3333333333333333333333333UnT)G '!ile(!!) L print&(XYcUtT5 !!3W*al)G !! M !ead3Wne2tG P print&(XUn 333333333333333333333333UnT)G getc!()G 6 M @Se$pty(!ead1)G i&(Z6) L print&(XUn ,e$o*ing t!e c!aracter &ro$ t!e @ueue _T)G c1 M pop1(!ead1)G P P'!ile(Z6)G ans=i> M JU+EG print&(XTH1 A4. I.CUnT)G &or(iM+G ans=i> ZM JU+EG iOO) print&(XYcUtT5ans=i>)G P

QR &unction &or D1PTH 4I,.T .1A,/H RQ *oid d&s(0H !eader) L c!ar c15 ans=3+>G int 6M+5 iM+G 0, tG 0H tt$pG .T\ !ead15 !!G !ead1 M createst()G tt$p M !eader3Wdo'nG '!ile(tt$p) L tt$p3W&lag M +G tt$p M tt$p3Wdo'nG P tt$p M !eader3Wdo'nG print&(X1nter t!e c!aracter you 'ant to start &ro$UnT)G &lus!all()G c1Mgetc!ar()G do L tt$p M &ind(c15!eader)G print&(XYcUnT5 tt$p3W*erte2)G ans=iOO>M tt$p3W*erte2G tt$p3W&lag M 1G t M tt$p3Wrig!tG '!ile(t) L tt$pM &ind(t3W*erte25 !eader)G i&(tt$p3W&lag MM +) L pus!(t3W*erte25 !ead1)G print&(XUn Yc *erte2 is pus!ed in t!e stac6 UnT5 t3W*erte2)G

tt$p3W&lag M 1G getc!()G P t M t3W rig!tG P print&(X no' t!e stac6 is _UnT)G !!M !ead13Wne2tG print&(X3333333333333333333333333UnT)G '!ile(!!) L print&(XYcUtT5 !!3W*al)G !! M !ead3Wne2tG P print&(XUn 333333333333333333333333UnT)G getc!()G 6 M st6Se$pty(!ead1)G i&(Z6) L print&(XUn ,e$o*ing t!e c!aracter &ro$ t!e stac6 _T)G c1 M pop(!ead1)G P P'!ile(Z6)G ans=i> M JU+EG print&(XTH1 D4. I.CUnT)G &or(iM+G ans=i> ZM JU+EG iOO) print&(XYcUtT5ans=i>)G P QR #AI; RQ $ain() L 0H !eaderG c!ar c15c2G int c!oiceG !eader M create1()G

do L print&(XDHI/H /HA,A/T1,. A,1 ADVA/1;T UnT)G &lus!all()G c1 M getc!ar()G &lus!all()G c2 M getc!ar()G searc!(c15c25!eader)G searc!(c25c15!eader)G print&(XD8 F87 DA;T T8 /8;TI;71 [ UnT)G &lus!all()G P'!ile(getc!ar() MM JyE)G display(!eader)G do L print&(XUnUn RRRRRRR $enu RRRRRRU;T)G print&(XU; 1;T1, F87, /H8I/1UnT)G print&(X1CRRRA4.RRRUnT)G print&(X2CRRRD4.RRRUnT)G print&(X3C?7ITUnT)G print&(XRRRRRRRRRRRRRRRRRRRRRRRRUnT)G scan&(XYdT5 :c!oice)G s'itc!(c!oice) L case 1C -&s(!eader)G -rea6G case 2C d&s(!eader)G -rea6G P P'!ile(c!oice ZM 3)G P

8utput C

DHI/H /HA,A/T1,. A,1 ADVA/1;T[ aD8 F87 DA;T T8 /8;TI;71[ y DHI/H /HA,A/T1,. A,1 ADVA/1;T[ ac D8 F87 DA;T T8 /8;TI;71[ y DHI/H /HA,A/T1,. A,1 ADVA/1;T[ ad D8 F87 DA;T T8 /8;TI;71[ y DHI/H /HA,A/T1,. A,1 ADVA/1;T[ -c D8 F87 DA;T T8 /8;TI;71[ y DHI/H /HA,A/T1,. A,1 ADVA/1;T[ -e D8 F87 DA;T T8 /8;TI;71[ y DHI/H /HA,A/T1,. A,1 ADVA/1;T[ e& D8 F87 DA;T T8 /8;TI;71[ y DHI/H /HA,A/T1,. A,1 ADVA/1;T[ &g D8 F87 DA;T T8 /8;TI;71[ n a MMW d33W c 33W - 33W ;7<< - MMW e33W c 33W a 33W ;7<< c MMW -33W a 33W ;7<< d MMW a 33W ;7<< e MMW & 33W - 33W ;7<< & MMW g 33W e 33W ;7<< g MMW & 33W ;7<< RRRRRRRR #1;7 RRRRRRRR 1;T1, F87, /H8I/1 1CRRRA4.RRR 2CRRRD4.RRR 3C?7IT

RRRRRRRRRRRRRRRRRRRRRRR 1 1;T1, TH1 /HA,A/T1, F87 DA;T T8 .TA,T 4,8# a a d *erte2 is pus!ed in t!e @ueue c *erte2 is pus!ed in t!e @ueue - *erte2 is pus!ed in t!e @ueue ;o' t!e @ueue is _ 3333333333333333333333333333333 dc3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e @ueue _ d ;o' t!e @ueue is _ 3333333333333333333333333333333 c3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e @ueue _ c ;o' t!e @ueue is _ 3333333333333333333333333333333 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e @ueue _ e *erte2 is pus!ed in t!e @ueue ;o' t!e @ueue is _ 3333333333333333333333333333333 e 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e @ueue _ e & *erte2 is pus!ed in t!e @ueue

;o' t!e @ueue is _ 3333333333333333333333333333333 & 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e @ueue _ & g *erte2 is pus!ed in t!e @ueue ;o' t!e @ueue is _ 3333333333333333333333333333333 g 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e @ueue _ g ;o' t!e @ueue is _ 3333333333333333333333333333333 3333333333333333333333333333333 TH1 A4. I. _ adc-e&g RRRRRRRR #1;7 RRRRRRRR 1;T1, F87, /H8I/1 1CRRRA4.RRR 2CRRRD4.RRR 3C?7IT RRRRRRRRRRRRRRRRRRRRRRR 2 1;T1, TH1 /HA,A/T1, F87 DA;T T8 .TA,T 4,8# a a d *erte2 is pus!ed in t!e stac6 c *erte2 is pus!ed in t!e stac6 - *erte2 is pus!ed in t!e stac6 ;o' t!e stac6 is _ 3333333333333333333333333333333

-cd 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e stac6 _ e *erte2 is pus!ed on t!e stac6 ;o' t!e stac6 is _ 3333333333333333333333333333333 ecd 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e stac6 _ e & *erte2 is pus!ed on t!e stac6 ;o' t!e stac6 is _ 3333333333333333333333333333333 &cd 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e stac6 _ & g *erte2 is pus!ed in t!e stac6 ;o' t!e stac6 is _ 3333333333333333333333333333333 gcd 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e stac6 _ g & *erte2 is pus!ed in t!e stac6 ;o' t!e stac6 is _ 3333333333333333333333333333333 cd 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e stac6 _ c ;o' t!e stac6 is _ 3333333333333333333333333333333

d 3333333333333333333333333333333 ,e$o*ing t!e c!aracter &ro$ t!e stac6 _ d ;o' t!e stac6 is _ 3333333333333333333333333333333 3333333333333333333333333333333 TH1 D4. I. _ a-e&gcd

RRRRRRRR #1;7 RRRRRRRR 1;T1, F87, /H8I/1 1CRRRA4.RRR 2CRRRD4.RRR 3C?7IT RRRRRRRRRRRRRRRRRRRRRRR 3 T!e purpose o& t!e a-o*e progra$ is to $a6e t!e !eader &a$iliar 'it! t!e generation concepts &or t!e lin6ed lists as 'ell as t!e use o& stac6s and @ueues &or t!e operations on t!e grap!. T!e output is sel&3e2planatory. As you read t!e output o& t!e progra$5 you 'ill understand t!e total procedure or t!e logic to get t!e A4. or D4. o& t!e grap!. '-!- ;t)er *as$s 8or *)e (rap)s? .o$e ot!er &unctions5 '!ic! are associated 'it! grap! &or sol*ing t!e pro-le$s areC 31.*o find t)e degree of t)e verte7 T!e degree o& t!e *erte2 is de&ined as a nu$-er o& *ertices '!ic! are ad9acent to gi*en *erte25 in ot!er 'ords5 it is nu$-er o& 1Es in t!e ro' o& t!at

*erte2 in t!e ad9acency $atri2 or it 'ill -e nu$-er o& nodes present in t!e ad9acency list o& t!at *erte2. 32.*o find t)e nu24er of edgesAy !and s!a6ing le$$a 5 'e 6no' t!at t!e nu$-er o& edges in a grap! is !al& o& t!e su$ o& degrees o& all t!e *ertices. 33.*o print a pat) fro2 one verte7 to anot)erHere 'e are re@uired to &ollo' t!e a-o*e algorit!$ o& A4. suc! t!at one o& t!e *ertices is t!e starting *erte2 &or t!e algorit!$ and t!e process 'ill continue till 'e reac! t!e second *erte2. 34.*o print t)e 2u/tip/e pat)s fro2 one verte7 to anot)erT!e pre*ious algorit!$ s!ould -e used in so$e di&&erent &or$ so t!at 'e can get $ultiple pat!s. 35.*o find t)e nu24er of co2ponents in a grap)In t!is case 'e 'ill again use t!e A4.5 and c!ec6 t!e *isited array5 i& it does not contain all t!e *ertices $ar6ed as *isited t!en incre$ent t!e co$ponent counter -y 1 and &ro$ any o& t!e *erte2 '!ic! is not *isited5 restart t!e A4.. ,epeat till all t!e *ertices are *isited.

36.*o find t)e critica/ vertices and edgesT!e *erte2 '!ic! '!en re$o*ed &ro$ t!e grap!5 lea*es t!e grap! as disconnected5 'ill -e ter$ed as critical *erte2. To &ind t!e critical *erte2 'e s!ould &irst re$o*e eac! *erte2 and c!ec6 t!e nu$-er o& co$ponents o& t!e re$aining grap!. I& t!e grap!5 '!ic! is re$aining5 is not a connected grap!5 t!e *erte25 '!ic! is re$o*ed5 is a critical *erte2. .i$ilarly re$o*al o& an edge &ro$ t!e grap!5 i& increases t!e nu$-er o& co$ponents5 it 'ill -e 6no'n as critical edge. I& 'e try to c!ec6 '!et!er a particular *erte2 or edge is critical5 t!en re$o*e t!e sa$e and rerun t!e progra$ &or &inding t!e nu$-er o& co$ponents.

67ercise? 37.DAP to accept t!e grap! &ro$ t!e user along 'it! 'eig!t attac!ed to eac! edge . Accept a pat! &ro$ t!e user '!ic! is in t!e &or$ o& se@uence *ertices and 'e are re@uired to print t!e 'eig!t o& t!at pat!. Session : *rees (Part 1) During t)is session ou 3i// /earn a4out 0rees. 4ooted tree and binary trees. 2inary search tree. 0raversals of the trees. Preorder 0raversal recursive and iterative. Postorder 0raversal recursive and iterative. /norder 0raversal recursive and iterative. 1perations on trees.

7-1- Introduction 7ntil no' 'e !a*e seen t!e data structures5 '!ic! 'ere -asically connected linearly. Aut $any ti$es 'e are re@uired to !a*e t'o $ore pat!s &ro$ t!e correct Jo-9ectE. It is not t!e linear tra*ersal -ut t!ere 'ill -e $ultiple c!oices. T!e data o-9ect could -e connected to $ore t!an 2 data o-9ect. A Graph is defined as a collection of vertices and edges D! FG, !H, where G is set of vertices and ! is set of edge. An !ge is defined as pair of vertices, which are connected. /f the edge has direction, the graph is (directed graph) and edge will be ordered pair of vertices. It is also possi-le to tra*el &ro$ one *erte2 to ot!er *ertices t!en t!e grap! is 6no'n as connected grap!. I& t!e pat! t!at 'e &ollo' ta6es us -ac6 to start *erte25 t!en 'e say t!at t!ere e2ists a cycle or a closed path or circuit. e.g. A 04!! is defined as a connected graph without a circuit. A I

V D \

A / 4

H B

8ig 1- *ree 7-2- ,ooted *ree A tree is which one verte$ is distinguished from others and called as "oot is #nown as a "oote! #ree. I& 'e consider t!e tree to -e a directed grap!5 t!en e*ery *erte2 'ill !a*e inco$ing degree as 'ell as outgoing degree. Inco$ing degree is t!e nu$-er o& nodes t!at consider t!is node as ter$inal node. 8utgoing degree is t!e nu$-er o& nodes consider t!is node as t!e initial node. Degree is t!e nu$-er o& edges incident as a *erte2. i.e. it is t!e su$ o& inco$ing degree and t!e outgoing degree. 8-ser*e t!at t!e root is a *erte2 !a*ing inco$ing degree ero. e.g.

! " # $ % & ' ( I ) * L

In 0 1 1 1 1 1 1 1 1 1 1 1

Ou 2 3 1 0 0 0 4 0 0 0 0 0

I <

8ig 2- ,ooted *ree

8ig 3- Inco2ing and outgoing

vertices of tree in fig 2 <et us ta6e a loo6 ate so$e ot!er properties o& trees. 1. A connected grap! on *ertices !a*ing (131) edges is 6no'n as T,11. 2. A grap! in '!ic! t!ere is a uni@ue pat! -et'een any pair o& *ertices is a T,11. 3. It is a $ini$ally connected grap!. 8-ser*e t!at all t!e ot!er *ertices !a*e t!e inco$ing degree as 1. D!en inco$ing degree is $ore t!an 1. 'e can say t!at t!ere is $ore t!an one 'ay to reac! t!e *erte2 and it 'ill not -e a tree. Also o-ser*e t!at5 su$ o& inco$ing degrees M su$ o& out co$ing degrees. M nu$-er o& edges M nu$-er o& *ertices31. F inco$ing degrees M 11. F outgoing degrees M2O3O1O+O+O+O4O+O +O+O4O+ M 11. T!e node 'it! inco$ing degree J eroE is a ,oot node. i.e. A 'ill -e t!e J,88TE. T!e nodes 'it! outgoing degree J eroE are 6no'n as Jlea& nodesE e.g.5 D51545H5<5V. 4ro$ a node i& t!e outgoing edges are reac!ing t!e *ertices *15*25 .5etc. t!en *15*2 etc. 'ill -e c!ildren o& t!at node e.g. A and / are c!ildren o& A and < is t!e c!ild o& \. 7-3- Dinar *ree 2inary 0ree is a rooted tree in which root has ma$imum two children such that each of them again is a binary tree. T!e de&inition is a recursive definition as 'e use t!e 'ords JAinary TreeE to de&ine t!e -inary Tree. De also say t!at a J?U** 04!!G is a Ainary Tree. In Ainary Tree5 t!e outgoing degree o& eac! *erte2 can -e $a2i$u$ t'o. T!e c!ildren are identi&ied as le&t c!ild and rig!t c!ild respecti*ely. T!e tree in t!e pre*ious diagra$ is de&initely not a Ainary Tree -ecause A and B !a*e $ore t!an t'o c!ildren. It is not necessary t!at nodes s!ould !a*e t'o c!ildren. De $ay !a*e a -inary tree in '!ic! none o& t!e nodes !a*e t'o c!ildren.

e.g.

P ? , T 7 ] 0 D

8ig !- Dinar *ree T!e structure used &or de&ining t!e nodes &or a Ainary Tree is s!o'n -elo'C struct -inStr L int dataG struct -inStr Rle&t5R rig!tG P Here 'e 'ill !a*e data &ield o& any type and si e5 and t'o pointers are used to point to t!e le&t c!ild and rig!t c!ild respecti*ely. T!is structure is again dyna$ic in nature and t!ere is no li$itation on nu$-er nodes5 and 'e can go on -uilding t!e tree in any &or$. D!en t!e tree is not re@uired 'e can &ree all t!e nodes so t!at t!e $e$ory can -e utili ed &or so$e ot!er process. De 'ill use a !eader node in case o& a -inary tree. It is not co$pulsory -ut it !elps us to 'rite easier algorit!$s. T!ere&ore 'e 'ill use t!is concept o& !eader nodes in our discussions. T!e root o& t!e tree 'ill -e attac!ed to t!is node. It can -e connected to t!e !eaderEs le&t or rig!t. It 'ill -e t!e progra$$erEs decision. 8& course t!e !eader does not contain any data. 7-! Creation of Dinar *ree As 'e !a*e pre*iously created t!e lin6ed list5 'e are a'are o& procedure &or creation o& a list. During t!e creation 'e are re@uired to create ne' locations or nodes5 enter t!e data into t!e$ and set t!e proper lin6s so t!at t!e pat! 'ill -e set to access t!e data. In case o& lin6ed list it 'as easy -ecause at particular position o& t!e list5 'e !a*e only one 'ay or one pointer '!ere t!e ne' node can -e attac!ed. Aut in case o& -inary trees at any node 'e !a*e t'o c!oices to attac! t!e node. Hence '!ile creating t!e tree5

'e 'ill !a*e to as6 t!e user as '!ere a particular node s!ould -e attac!ed5 to t!e le&t or to t!e rig!t. T!us 'e can 'rite t!e algorit!$ &or creating t!e -inary tree 6eeping t!is concept in $ind. T!e algorit!$ &or t!e creation o& t!e tree is as &ollo's 1. /reate a node say ne'Snode. .et te$p to !eader. /!ec6 '!et!er t!e te$p !as le&t c!ild i& so5 ne'Snode 'ill -e attac!ed as le&t soon to te$p. I& te$p !as le&t c!ild5 it indicates t!at t!e tree is present5 'e $o*e to t!e le&t c!ild o& te$p. i.e. set te$p to te$pEs le&t. Display t!e *alue o& te$pEs data and as6 '!et!er t!e ne' Snode s!ould -e attac!ed to le&t or rig!t o& te$p. I& t!e respecti*e c!ild e2ists t!en $o*e to t!at c!ild ot!er'ise attac! t!e ne'Snode as t!e c!ild re@uested -y t!e user. ,epeat step 45 till ne'Snode gets attac!ed. As6 t!e user '!et!er t!ere are $ore *alues[ I& yes t!an go to step 1. %. .top. /reation is o*er. 4or t!is algorit!$ 'e assu$e t!at t!e !eader node !as -een crated -e&ore 'e -egin creation o& t!e tree. Also 'e 'ill 'rite a &unction to generate a ne'Snode. struct -inS tr I getJne'Snode L struct -inS tr R te$pG te$p M(struct -in Str :)$alloc(si e o& (struct -inStr))G te$p a le&t M ;7<<G te$p a rig!t M ;7<<G return (te$p)G P Suppose 3e dec/are a ne3 t pe for t)e a4ove structure as DI*,9 3)ic) is a pointer t pe t)en t)e function cou/d 4e re3ritten as typede& struct -in Str R AIT,G AIT, getSne'Snode() L AIT, te$pG te$p M(AIT,)$alloc(si eo&(struct -inStr ))G te$pale&t M te$parig!t M ;7<<G return (te$p)G P

Dit! t!is 'e 'ill 'rite t!e create &unction. *oid createStr(AIT, !) L AIT, te$p5 ne'SnodeG int c!6G c!ar cG do L ne'Snode M getSne'Snode()G c!6 M +G te$p M !G scan&(XYdT5 :ne'Snodeadata)G i& (te$pale&t ZM ;7<<) te$p M te$p a le&tG else te$p a le&t M ne' S nodeG '!ile (c!6 M M +) L print& ( X T!e current node is YdUn T5 te$pa c!6)G print& ( XD!et!er t!e ne' node s!ould -e attac!ed to le&t or rig!t[UnT)G c M getc!()G i& (c MMJ<E) i& (te$pale&t M ;7<<) te$p M te$pale&tG else L te$pale&t M ne'SnodeG c!6 M 1G P else i& (te$parig!t M ;7<<) te$p M te$parig!tG else L te$p a rig!t M ne' S nodeG c!6 M 1G P P print& ( X Any $ore node[ UnT)G c M getc! ( )G P'!ile ( c MMJyE)G P

8-ser*e t!at t!e tree '!ic! 'e are creating is as gi*en -y t!e user. 1*ery ti$e &or attac!ing a ne'Snode5 'e co$e &ro$ t!e !eader5 as6ing '!et!er to attac! to le&t or rig!t. T!oug! t!e trees get created success&ully5 '!ile displaying t!e$5 'e 'ill !a*e to &ace a lot o& trou-le. I& t!e generated tree is 21 " 4 12 13 8ig 5- Dinar *ree ;or$ally 'e pre&er to print t!e tree in le*el 'ise &or$at as s!o'nC 21 " 4 12 13 ) 1% 1+ 1+ ) 1% 35 24 31 3+

35

31

3+

Aut t!is output does not gi*e us t!e correct idea o& t!e tree. T!e sa$e output 'ill -e generated e*en &or t!e &ollo'ing tree. 21 " 4 1% ) 24

12

1+ 13

35 31

3+

8ig '- Dinar *ree Anot!er 'ay 'ould -e rat!er descripti*e ;ode ;ode ;ode ;ode ;ode ;ode ;ode ;ode 21 " ) 4 1% 24 12 1+ C C !as !as !as !as !as !as !as !as le&tc!ild le&tc!ild le&tc!ild le&tc!ild le&tc!ild le&tc!ild le&tc!ild le&tc!ild "5 45 1%5 125 355 315 ;I<5 ;I<5 rig!tc!ild rig!tc!ild rig!tc!ild rig!tc!ild rig!tc!ild rig!tc!ild rig!tc!ild rig!tc!ild ) ;I< 24 1+ ;I< 3+ 3 ;I<

8-ser*e t!at t!e se@uence o& t!e nodes is still le*el 'ise -ut assertion in&or$ation 'ill gi*e uni@ue tree. 7-5 Dreadt) 8irst Searc) T!is is (le*el3'ise printing) also 6no'n as t!e Areadt! 4irst .earc! A4.. To i$ple$ent it5 &ollo'ing algorit!$ 'ill -e use&ul5 .teps C 1. te$p 'ill point to !eaderEs le&t. 2. 7se @ueue &or t!e operation. 3. pus! te$p in t!e @ueue. 4. pop a node &ro$ t!e @ueue say te$p. 5. print t!e data o& node te$p. ". i& te$p !as le&t c!ild5 pus! it into t!e @ueue. %. i& te$p !as rig!t c!ild5 pus! it into t!e @ueue. (. repeat t!e process &ro$ step 4 till t!e @ueue -eco$es e$pty. ). .top.

Here 'e are using t!e data structure J@ueueE &or t!e particular operation on tree. To declare t!e structure o& t!e @ueue 'e 'ill !a*e to decide t!e type o& data5 '!ic! 'ill go into t!e @ueue[ .!ould it -e sa$e as data type in t!e node o& t!e tree[ I& you t!in6 t!e ans'er is JyesE t!en o-ser*e t!at 'it! &irst pus! operation5 t!e data i.e. *alue 21 'ill -e pus!ed into t!e @ueue. T!en 'e pop t!e *alue and print it. Aut i& 'e 'ant to go to t!e le&t c!ild t!en re$e$-er t!at t!e data cannot in&or$ a-out t!e address o& le&t c!ild. Hence 'e s!ould pus! t!e node o& t!e tree into t!e @ueue or in ot!er 'ords t!e pointer to t!e node in t!e tree 'ill -e t!e data ele$ent &or node in t!e @ueue. I& 'e are i$ple$enting t!e @ueue -y array t!en t!e @ueue 'ill -e declared as AIT, @ueS-&s=.II1>G and i& 'e are using lin6ed list t!en struct @ueSL AIT, t*alG struct @ueS- Rne2tG P Dit! t!is5 'e s!ould accordingly use t!e pus! and pop &unctions to run t!e progra$ &or -&s. *oid -&s (AIT, !) L AIT, te$pG te$p M ! a le&tG pus!(te$p)G '!ile(Z @e$pty()) L te$p M pop()G print&(XYdQnT5 te$p a data)G i& (te$p a le&t ZM ;7<<) pus! (te$p a le&t)G i& (te$p a rig!t ZM ;7<<) pus! (te$p a rig!t)G P P T!is J-&sE &unction 'ill -e *ery use&ul as t!ere are $any applications '!ere J-&sE 'it! little additional code 'ill gi*e us t!e ans'ers.

e-gTo count nu$-er o& nodes in t!e tree5 'e 'ill 9ust use -&s along 'it! an additional counter. T!e counter incre$ent state$ent 'ill si$ply replace t!e print&() in a-o*e code and a&ter t!e co$pletion o& loop5 'e $ay return t!e counter '!ic! contains t!e nu$-er o& nodes. int countSnodes (AIT, n) L AIT, te$pG int cnt M oG C C '!ile(Z@e$pty()) L te$p M pop( )C cnt OOG C C P return(cnt)G P .uppose 'e 'ant to print t!e nodes on eac! le*el on sa$e line and o& ne2t le*el on ne' line. 8-ser*e t!e nodes 'ill go into t!e @ueue in t!e &ollo'ing $anner. 21 " ) 4 1% 24 12 1+ 35 31 3+ 3 ) 4 1% 24 12 1+ 35 31 3+ 13

QR rest all is sa$e as t!at o& -&s

QR sa$e as t!at o& -&s RQ

24 12 1+ 35 31 3+ 13

1+ 35 31 3+ 13

3+ 13

8-ser*e t!at t!ere is no distinction -et'een t!e *alues dependent t!eir le*els. De s!ould place so$e deli$iter indication end o& t!e le*el in @ueue5 say H. ;o' t!e process 'ill -e seen as -elo' C

21 . " ) . 4 1% 24 . 12 1+

. " ) . 4 1% 24 . 12 1+ 35

) . 4 1% 24 . 12 1+ 35 31

24 . 12 1+ 35 31 3+

1+ 35 31 3+ .

3+ . 13

8-ser*e t!at '!ene*er 'e pop H5 t!e le*el is o*er and 'e s!ould go to line &or printing. Also t!is H s!ould -e pus!ed again into t!e @ueue. D!en poped and t!e @ueue is e$pty 'e s!ould stop. As t!e @ueue contains t!e pointer H5 it also s!ould -e a pointer o& sa$e type -ut !as to -e treated in a special 'ay. <et us ta6e it as !eader. T!e &unction 'ill -e $odi&ied as &ollo'sC *oid -&sSle*el (AIT, !) L AIT, te$pG te$p M ! a le&tG pus! (te$p)G pus! (!)G te$p M pop()G '!ile (Z @e$pty()) L i& ( te$p ZM !) L print& (XYdT5 te$p a data)G i& ( te$p a le&t) pus! ( te$p a rig!t ) i& (te$p a rig!t)G pus! (te$p a rig!t)G P else L pus! (te$p)G print& (XUnT)G

P te$p M pop ( )G P P Again t!e a-o*e &unction can -e $odi&ied so t!at 'e can count nu$-er o& nodes per le*els in a tree. As 'e !a*e seen -e&ore5 '!ene*er !eader is encountered5 'e understand t!at t!e le*el !as ended. 1*ery ti$e '!en 'e recei*e t!e !eader node 'e 'ill &irst reset t!e counter to ero and incre$ent t!e counter till 'e again recei*e !eader. Print t!e contents o& t!e !eader at t!at ti$e5 '!ic! represents t!e nu$-er o& nodes in t!at le*el. .uppose 'e 'ant to searc! &or a particular data in t!e tree5 'e can also use t!e -readt! &irst searc!. Here 'e use t!e searc!5 '!ic! is along t!e -readt! o& t!e tree. De s!ould pass t!e !eader as 'ell as *alue &or searc!ing to t!e &unction. It can return 1 to + or pointer or ;7<< dependent on presence o& *alue. int -&Ssearc! (AIT, !5 int *al) L AIT, te$pG te$p M ! a le&tG pus! (te$p)G '!ile (Z @e$pty()) L te$p M pop()G i& (te$p a dat MM *al) return (1)G i& (te$p a le&t) pus! (te$p a le&t)G i& (te$p a rig!t) pus! (te$p a rig!t)G P return ( + )G P I& 'e are re@uired to count t!e nu$-er o& lea& nodes in t!e tree t!e e*ery ti$e 'e pop a node &ro$ t!e @ueue5 c!ec6 '!et!er it is a lea& node5 i& yes you incre$ent count. int countSlea& (AIT, !) L 3333 3333 '!ile (Z@e$pty())

L te$p M pop()G i& ((Zte$pale&t)::(Zte$parig!t)) 3333 3333 P return (count)G P In t!e si$ilar 'ay 'e can go &or counting t!e nodes !a*ing only ones and nodes5 '!ic! !a*e -ot! t!e c!ildren. T!e progra$ a!ead gi*es t!e co$plete idea a-out creation o& t!e tree and so$e ot!er &unctions. T!e &unctions are $odi&ied to s!o' a &riendly display. Here 'e are using t!e goto2y() &unction -y '!ic! 'e can place t!e output at t!e yt! ro' and 2t! /olu$n on t!e screen. T!ere are in all (+ colu$ns and 25 ro's. QR /reation -y -inary tree5 position de&ined -y t!e user RQ K include Nstdio.!W K include Nalloc.!W K include Nconio.!W typede& struct tree L int *alG struct tree Rle&t5R rig!tG PRT,G T, !eaderG typede& struct @ue L T, nodeG struct @ue Rne2tG PR?G QR t!e data in case o& @ueue node 'ill -e pointer to t!e node o& t!e tree RQ ? !ead@5 lastG QR !eader o& t!e @ueue and t!e last position are declared as glo-al RQ QR !eader &or t!e tree is glo-al RQ

*oid create@() L !ead@ M $alloc(si eo&(struct @ue))G !ead@3Wne2t M ;7<<G last M !ead@G QR initially !eader itsel& 'ill -e t!e end o& t!e @ueueRQ P int @e$pty() L return(!ead@3Wne2tMM;7<<)G P T, poppp() L ? t@G QR pop &unction 'ill al'ays return t!e data RQ T, tnG t@ M !ead@3Wne2tG tn M t@3WnodeG !ead@3Wne2t M !ead@3Wne2t3Wne2tG &ree(t@)G return(tn)G QR in t!is case t!e data is pointer to t!e node o& tree RQ P *oid pus!(T, n) L ? ne'@G ne'@ M $alloc(si eo&(struct @ue))G ne'@3Wnode M nG ne'@3Wne2t M last3Wne2tG last3Wne2t M ne'@G last M ne'@G P T, getnode() L T, rG r M $alloc(si eo&(struct tree))G goto2y(2+51))G print&(X1nter t!e *alue_UnT)G

goto2y(2+52+)G scan&(XYdT5 :r3W*al)G goto2y(2+51))G print&(X T)G goto2y(2+52+)G print&(X T)G r3Wle&t M r3Wrig!t M ;7<<G return(r)G P T, create() L int &lag5 i5 95 65 p5 @5 'ayG c!ar cG T, !eader5 te$p5 ne'G !eader M $alloc(si eo&(struct tree))G goto2y(3(51)G print&(XH1AD1, T)G !eader3Wle&t M ;7<<G

do L i M 4+G 9 M 2G 6 M 2+G ne' M getnode()G &lag M +G i& (!eaderale&t MM ;7<<) L !eader3Wle&t M ne'G goto2y(i59)G print&(XYdT5 ne'3W*al)G P else L te$p M !eader3Wle&tG

do L goto2y(2+51))G print&(X#801 T8 <14T 8, ,IBHT (+Q1)T)G goto2y(2+52+)G scan&(XYdT5 :'ay)G goto2y(2+51))G print&(X T)G i&('ay MM +) L goto2y(4+522)G print&(X#o*ing to le&tc!ild_T)G goto2y(4+522)G print&(X T)G &or( p MiG p W i365 p33) L goto2y(p59O1)G print&(XYdT5 ne'3W*al)G goto2y(p59O1)G print&(X T)G P goto2y(i36Q259O1)G print&(XQT)G i M i36G 9 M 9O2G 6 M 6Q2G i&(te$p3Wle&t MM ;7<<) L te$pale&t M ne'G print&(XYdT5 ne'3W*al)G &lag M 1G P else L goto2y(i59)G te$p M te$pale&tG print&(XYdT5 te$p3W*al)G P P else

L &or( p MiG p W i365 p33) L goto2y(p59O1)G goto2y(4+522)G print&(X#o*ing to rig!tc!ild_T)G goto2y(4+522)G print&(X T)G &or( p MiG p W iO65 pOO) L goto2y(p59O1)G print&(XYdT5 ne'3W*al)G goto2y(p59O1)G print&(X T)G P goto2y(iO6Q259O1)G print& (XUUT)G iMiO6G 9M9O2G 6M6Q2G i&(te$p3Wrig!tMM;7<<) L goto2y(i59)G te$p3Wrig!tMne'G print&(XYdT5 ne'3W*al)G te$p3Wrig!tMne'G &lagM1G P else L goto2y(i59)G te$pMte$p3Wrig!tG print&(XYdT5 te$p3W*al)G P P P'!ile(&lagM M+)G P goto2y(4+51))G

print&(XAny$ore FQ;T)G goto2y(4+52++G &lus!all()G c M getc!ar()G goto2y(4+51))G print&(X T)G goto2y(4+52+)G print&(X T)G P'!ile(cMMJyEHH cMMJFE)G return(!eader)G P T, le&t$ost(T, te$p) L '!ile(te$p3Wle&tZM;7<<) te$pMte$p3Wle&tG return(te$p)G P T, rig!t$ost(T, te$p) L '!ile(te$p3Wrig!tZM;7<<) te$pMte$p3Wrig!tG return(te$p)G P $ain() L T, tG clrscr()G !eader M create()G t M !eader3Wle&tG create@()G pus!(t)G goto2y(1+524)G '!ile(Z@e$pty()) L tMpoppp()G print&(XYdUtT5 t3W*al)G

i&(t3Wle&t) pus!(t3Wle&t)G i&(t3Wrig!t) pus!(t3Wrig!t)G P print&(XYdUnT5 t3W*al)G P T!e output o& t!e a-o*e progra$ is not attac!ed -ecause t!e output o& is a dyna$ic one. 7sing t!e screen coordinates5 an atte$pt is $ade to s!o' t!e actual creation o& t!e tree. Here you can see !o' a particular tree is -eing -uilt. T!is interacti*e progra$ 'ill -e *ery use&ul '!o -elie*e in t!e sel&3learning and understanding process. In t!e a-o*e pro-le$ 'e 'ere 9ust creating a tree. It 'as a -inary tree and t!e nodes 'ere placed at t!e users 'is!. T!ese nodes !a*e t!e relation as parent and c!ild -ut t!at relation purely set -y t!e user and data in t!e node !as 9ust no role to play. 7-'- Dinar Searc) *rees I& 'e t!in6 o& attac!ing t!e nodes in suc! a $anner t!at t!eir positions decided -y t!e data contained in t!e node and also t!at i& 'e are at a particular side it s!ould -e possi-le &or us to 6no' '!ere a node o& a particular data $ay -e present. T!is is possi-le -y using t!e concept o& a -inary searc! tree. A Ainary Tree in '!ic! t!e nodes are positioned in t!e le&t su- tree or rig!t sutree dependent on t!e *alue o& so$e 6ey5 '!ic! is present in t!e data5 is 6no'n as JAinary .earc! TreeE+. I& t!e 6ey *alue is less t!an t!e node *alue it s!ould -e placed in t!e le&t su- tree ot!er'ise in t!e rig!t su- tree. It is 6no'n as a .earc! Tree5 -ecause searc!ing &or t!e particular *alue in t!e nor$al tree 'ill -e as co$plicated as $o*ing to t!e dept! o& t!e tree. D!en Ainary Tree !as J$E le*els counting do'n +51525_.5 $5 t!e tree can !a*e $a2i$u$ (2$O1 1 ) nodes. T!e co$ple2ity &or searc!ing in Ainary Tree 'ill -e o& t!e order o& 2$O1 '!ere as i& it is a Ainary .earc! Tree5 it 'ill -e o& t!e order ($O1). (enera// 3e sa t)at once t)e root is created9 if t)e va/ue is /ess it s)ou/d go to t)e /eft su4 tree ot)er3ise to t)e rig)t su4 tree- 6ven if 3e c)ange t)e nature9 it 3i// sti// 4e sa2e i-e- Dinar Searc) *ree- Actua// 3it) t)e va/ue to 4e searc)ed9 t)e current node in t)e tree s)ou/d infor2 us9 in so2e 3a 9 3)et)er t)e va/ue s)ou/d 4e searc)ed in t)e /eft su4 tree or rig)t su4 tree of node-

1.g. 3 /onsider &igure 21 " 4 12 1+ 13 8ig '- Dinar *ree T!is as a searc! tree 'ill -e 21 " 4 ) 1% 31 12 1+ 13 3+ 24 35 1% 35 31 ) 24 3+

8ig 7- Dinar Searc) *ree Here 'e do not as6 t!e user a-out t!e position o& t!e node in t!e tree -ut it 'ill -e placed as per t!e rule. T!e a-o*e tree is constructed &ro$ t!e input se@uence as

21 " ) 4 1% 24 12 1+ 35 31 3+ 13. 4irst t!e root C 21 ;e2t *alue "5 '!ic! are5 less t!an 215 !ence it s!ould -e placed as le&t c!ild. ;o' *alue )5 less t!an 215 !ence as t!e le&t o& 21. <e&t c!ild e2ists5 t!ere&ore co$pare 'it! le&t c!ild i.e. "5 it is greater t!an "5 !ence 'ill -e on t!e rig!t ". 21 "

) 4or *alue 45 le&t o& 215 le&t o& " 21 "

4or *alue 1%5 le&t o& 215 rig!t o& "5 rig!t ) 21 " 4 )

1%

Hence t!e se@uence5 in '!ic! *alues are recei*ed5 'ill c!ange t!e nature t!e tree. e.g. i& t!e se@uence is 1% " ) 4 21 t!en t!e tree 'ill -e

1% " 4 ) 21

I& t!e *alues are ordered say ascending t!en t!e tree 'ill ta6e &ro$ o&

e.g. 4 " ) 1% 21 4 " ) 1% 21

7-7- Dinar Searc) *ree Creation ;o' let us consider t!e algorit!$ &or creating a Ainary .earc! Tree. Assu$ing t!at t!e &irst *alue is t!e root and *alues in le&t su- tree are al'ays less t!an t!e root node '!ereas *alues in t!e rig!t su- tree are greater t!an t!e root node *alue. Algorit!$ &or generating a -inary searc! treeC 1. 2. 3. 4. 5. ". %. /reate a ne' node. Accept t!e *alue &or ne'Snode. Attac! ne'Snode as le&t c!ild o& !eader. /rate a *alue &or ne'Snode. Accept t!e *alue &or ne'Snode. .et te$p to !eaderEs le&t (,88T). I& *alue o& ne'Snode is less t!an te$pEs *alue t!en i& te$p !as le&t c!ild5 $o*e te$p to te$pEs le&t 8t!er'ise attac! ne'Snode to te$pEs le&t and set t!e &lag to 1. else i& te$p !as rig!t c!ild5 $o*e te$p to te$pEs rig!t ot!er'ise attac! ne'Snode to te$pEs rig!t and set t!e &lag to 1. (. i& &lag is ero (i.e. ne'Snode is not yet attac!ed) goto step %. ). i& &lag is not ero t!en as6 t!e user '!et!er t!ere are $ore nodes[ I& yes t!en step 4. 1+. stop. QR &unction to create a -inary searc! tree RQ *oid createS-st (AIT, !) L AIT, te$p5 ne'SnodeG int &lagG ne'Snode M getSne'Snode()G QR create a ne' node RQ print& (X1nter t!e rootT)G scan& (XYdT5 :ne'Snode a data)G QR root node RQ ! a le&t M ne'SnodeG QR $a6e it as t!e le&t c!ild o& t!e !eader node RQ do L ne'Snode M getSne'Snode ( )G print& (X1nter t!e *alue o& nodeT)G te$p M ! a le&tG &lag M +G do

L i& (ne'Snode a data N te$p a data) QR i& *al is less t!an t!e parent $a6e it as le&t c!ild RQ i& (te$p a le&t) te$p M te$p a le&tG else L te$p a le&t M ne'SnodeG &lag M 1G P else i& (te$p a rig!t) QR i& t!e ne' node !as *alue $ore t!an t!e parent $a6e it a rig!t c!ild RQ te$p M te$p a rig!tG else L te$p a rig!t M ne'SnodeG &lag M 1G P P'!ile (&lag MM +)G print& (XAny $ore node [ FQ;T)G P'!ile(toupper(getc!())MMJFE)G P T!e a-o*e &unction can -e re'ritten in $ore reada-le &or$ 'it! t!e !elp o& s$aller &unctions.

*oid crateS-st ( AIT, ! ) L AIT, ne'SnodeG ! a le&t M getSne'Snode ( )G do L ne'Snode MgetSne'SnodeG insert(ne'Snode5 ! a le&t)G print& (XAny $ore nodes [ FQ;)G P'!ile(toupper(getc!()) MM JFE)G P

AIT, getSne'Snode() L AIT, te$pG te$p M getSne'Snode()G scan& (XYdT5 :te$padata)G P *oid insert (AIT, t5 AIT, ! ) L i& (t a data N ! a data) i& (! a le&t M 1G insert(t5 ! a le&t)G else i& (! a rig!t) insert (t5 ! a le&t)G else L ! a rig!t M tG returnG P else i& (! a rig!t) insert (t5 ! a rig!t)G else L ! a rig!t M tG returnG P P Here insert is recursi*e &unction5 '!ic! &ollo's &ro$ t!e recursi*e de&initions o& Ainary Tree. 7-8- Searc)ing a va/ue in a 4inar searc) tree As t!e na$e suggests5 t!e Ainary searc! trees !a*e t!e ai$ o& si$pli&ying t!e process o& searc!. Here t!e 'ord si$pli&y i$plies t!at 'e are re@uired to !a*e less nu$-er o& co$parisons to c!ec6 '!et!er a particular node *alue is present. ;o' i& 'e are re@uired to searc! &or a *alue in t!e tree5 'e can si$ply $odi&y t!e insert &unction as s!o'n -elo' int searc!(AIT, !5 int *al) QR to searc! a *alue

&ro$ node ! RQ L i& (! MM ;7<<) QR i& t!at node itsel& is ;7<<5 *alue is a-sentRQ return(+)G i& (!3Wdata MM *al) return ( 1 )G i& (*al N ! a data) QR i& *alue is less5 t!en searc! on <H.RQ return (searc! (! a le&t5 *al) )G else QR ot!er'ise searc! on ,H. RQ return (searc! (! a rig!t5 *al) )G P 8-ser*e t!at t!is is a recursi*e &unction. T!e description can -e gi*en to searc! &or a *alue in t!e su-tree 'it! root !. I& t!e tree is not e$pty t!en c!ec6 '!et!er t!e data is present at t!e root. I& t!e *alue is less t!an t!at o& *alue o& root t!en searc! in t!e le&t su-tree o& t!e root ot!er'ise searc! in t!e rig!t su-tree o& t!e root.T I& t!e passed node is ;7<<5 'e can conclude t!at t!e gi*en *alue is a-sent in t!e tree. I& *alue $atc!es 'it! ! a data5 'e return 1 saying t!at *alue is present. I& *alue is less t!en 'e searc! in le&t su-tree o& ! ot!er'ise in t!e rig!t su-tree o& !. 7-+ Dept) 8irst *raversa/ of t)e tree T!ere are $any ot!er 'ays o& tra*eling t!e tree. Dept! 4irst .earc! is one o& t!e 'ays in '!ic! t!e nodes can -e tra*eled. 4ro$ root 'e s!ould $o*e in t!e !ig!est le*el in one particular direction. e.g. In t!e pre*ious tree t!e D4. is 215"545)51%51251+51352453553153+. T!e Algorit!$ to get t!e D4. o& t!e tree is as &ollo's C 1. .et te$p to root. 2. Print te$pEs data. 3. Pus! te$pEs rig!t (i& e2ists) on t!e stac6. 4. .et te$p to te$pEs le&t .

5. I& te$p is not ;7<< t!en step 2. else pop a node &ro$ t!e stac6. ". T!e process continues till t!e stac6 is not e$pty. %. .top. Here 'e 'ill -e pus!ing t!e address on t!e stac6. T!e stac6 can -e i$ple$ented using array or lin6ed list. Assu$ing t!at t!e &ollo'ing &unctions are a*aila-le (pus!5 pop5 stac6Se$pty)5 t!e D4. &unction 'ill -e 'ritten as *oid d&s (T, !) L T, tG t M ! a le&tG do L print&(XYdT5 tadata)G i& (tarig!t) t M t arig!tG t M t ale&tG i& (t MM ;7<<) t M pop()G P'!ile(Zstac6Se$pty())G P T!e a-o*e &unction is not a recursi*e one. Aut 'e can e*en 'ritten recursi*e &unction o& t!e D4.. 7-1"- *ree *raversa/s *raversa/ is t)e 2ost co22on operation t)at can 4e perfor2ed on trees- In t)e traversa/ tec)ni@ue eac) node in t)e tree is processed or visited once9 s ste2atica// one after t)e ot)er- Processing 2a inc/ude <ust disp/a ing t)e contents of t)e node or assists in so2e ot)er operation- 8or t)e 4inar tree 3e a/so )ave t)ese i2portant traversa/s9 3)ic) are na2e/ 1. Preorder Tra*ersal 2. Postorder Tra*ersal 3. Inorder Tra*ersal

De are *ery $uc! a a'are o& t!e &act t!at t!ere 'ill -e le&t c!ild and rig!t c!ild &or any node in t!e -inary tree. T!e se@uence in '!ic! t!e node5 its le&t c!ild and rig!t c!ild are printed5 deter$ines t!e tra*ersal.

7-1"-1- Preorder traversa/ of t)e tree /n the Preorder traversal, the se"uence is in which the nodes are visited is root, left subtree and then right subtree. In s!ort it is ,oot%#eft%,ig)t. /onsider t!e treeC

A A / 4 8ig 8- Dinar *ree Processing order C A A / D 1 4 B T!e recursi*e &unction &or t!e preorder tra*ersal 'ill -eC *oid preSorder ( T, t ) L i& (t) L print&(XYdT5 tadata)GQR *isit t!e node RQ preSorder (tale&t)G QR *isit t!e le&t su-tree in preorder RQ preSorder (tarig!t)G QR *isit t!e rig!t su-tree in preorder RQ P 1 D B

P T!e recursi*e &unctions 'ill use t!e internal stac6. I& 'e o-ser*e t!e recursion o& t!e &unction5 'e &ind t!at t!ere is a recursi*e call 'it! le&t c!ild5 !ence e*ery ti$e le&t c!ild 'ill -e printed. D!en t!e node JtE does not !a*e le&t c!ild5 t!e control 'ill -e ta6en to t!e pre*ious call and t!e ne2t call is to t!e rig!t o& node JtE. Actually t!e Preorder tra*ersal o& t!e tree is sa$e as t!at o& D4. o& t!e tree. T!e d&s &unction 'ritten -e&ore is t!e non3recursi*e &unction &or Preorder tra*ersal. Algorit!$ &or non3recursi*e &unction5 &or preorder tra*ersal Assu$e t!at a pointer T points t!e root node5 . is a stac65 T8P is a top inde2 and P represents t!e current node in t!e tree. 1. Initiali ation is done &irst. I& TMM;ull t!e &unction prints it as a ;7<< tree. 8t!er'ise t!e node is pus!ed into t!e stac6. 2. ,epeat step 3 and step 4 '!ile t!ere is still so$e node le&t in t!e stac6 .i.e.5 T8P W+. 3. Pop t!e address &ro$ top o& t!e stac6 into t!e pointer P as PMpop(.5T8P). 4. ,epeat '!ile(PZM ;7<<) Print t!e data in t!e node P. I& P !as a rig!t c!ild call t!is &unction again and pus! t!e address o& t!is rig!t c!ild into t!e stac6. 8t!er'ise store t!e address o& t!e le&t c!ild into P. 5. stop. Fou $ay i$ple$ent t!e a-o*e &unction and test it 'it! *arious trees. 7-1"-2- Postorder traversa/ of t)e tree 0he Postorder traversal is *eft 4ight 4oot, i.e. traverse the left subtree, then the right subtree and then print the root. /onsider t!e treeC A A / 1 D B

4 8ig +- Dinar *ree Processing orderC / A 4 1 B D A QR recursi*e &unction to tra*erse tree in postorder RQ *oid postSorder ( T, t ) L i& (t) L postSorder (tale&t)G QR *isit t!e le&t su-tree in postorder RQ postSorder (tarig!t)G QR *isit t!e rig!t su-tree in postorder RQ print&(XYdT5 tadata)GQR *isit t!e node RQ P P T!e Iterati*e algorit!$ is as &ollo'sC Assu$e te$p is a pointer *aria-le t!at stores addresses o& nodes. 4lag is used to denote i& t!e node is *isited t'ice. Here eac! node 'ill -e stac6ed t'ice5 once '!en le&t su-tree is tra*ersed and once '!en its rig!t su-tree is tra*ersed. 8nly on co$pletion o& -ot! its su-trees5 '!ic! is denoted -y $a6ing t!e &lag as t'o5 t!e root *alue 'ill -e printed. 1. .et te$p to root. 2. Pus! te$p. 3. .et te$p to te$pEs le&t. 4. i& te$p is not ;7<< t!en step 2. 5. te$p M pop() ". i& (te$pEs &lag MM 2) t!en a. print te$pEs data else -. te$pEs &lag set to 2 c. pus! te$p d. te$p M te$pEs rig!t e. step 4

%. i& (stac6 is not e$pty ) t!en step 5. (. .top. T!e steps are s!o'n using &igures -elo'. /onsider t!e tree. %+ "+ 5+ 44 54 (+ (1 (4 8ig 1"- Dinar *ree ))

Initially te$p 'ill point to %+ _. .tep 1 4ollo'ing is t!e e2ecution o& t!e a-o*e algorit!$ as 'ell as t!e picture s!o's t!e se@uence in '!ic! t!e di&&erent steps in algorit!$ as 'ell as t!eir e&&ect. 4ro$ t!e root all t!e nodes 'ill -e pus!ed in t!e stac65 as 'e tra*el to t!e root o& eac! node5 till 'e get ;7<<. Stac$ %+ %+ "+ %+ "+ 5+ %+ "+ 5+ 44 44 ;7<< te2p %+ "+ "+ 5+ 5+ 44 1 f/ag 1 1 1 .tep 2 .tep 3 .tep 2 Step

1 .tep 3 1 .tep 2 1 .tep 3 .tep 2 .tep 3

D!en 'e get ;7<<5 'e pop a node &ro$ t!e stac65 i& its &lag is 15 'e c!ange it to t'o and pus! it -ac6 to t!e stac6. ;o' 'e tra*el to t!e rig!t c!ild o& t!e pop node i.e. 44Es rig!t in t!is case. %+ "+ 5+ 44 1 .tep 5

44 %+ "+ 5+ 44 44 ;7<< 2

2 .tep "..tep ".c .tep ".d

As 'e repeat t!e step o& pus!ing all t!e le&t c!ildren5 again on ;7<< 'e pop a node &ro$ t!e stac6. I& it !as &lag 25 print it. i.e. 44 in t!is case. %+ "+ 5+ 44 44 2 2 .tep 5 .tep ".a 44

;o' pop t!e ne2t node &ro$ t!e stac6 and repeat t!e '!ole process 5+ 1 5+ 2 &lag o& 5+5 !as c!anged to 2 and pus!ed in t!e stac6 %+ "+ 5+ 5+ 2 %+ "+ .tep 5 .tep ".-

.tep ".c

T!e ne2t node 'ill -e 5+Es rig!t c!ild i.e. 545 processing repeats &ro$ !ere 54 1 .tep ".d %+ "+ 5+ 54 54 1 .tep 2 52 1 .tep 3 %+ "+ 5+ 54 52 52 1 .tep 2 ;7<< .tep 3 %+ "+ 5+ 54 52 1 .tep 5 %+ "+ 5+ 54 52 52 52 ;7<< %+ "+ 5+ 54 52 2 .tep 5 2 2 .tep "..tep ".c .tep ".d

As 'e pop t!e node 525 its &lag is already 25 !ence it s!ould -e printed %+ "+ 5+ 52 54 2 2 .tep ".a 52 .tep 5

As 'e pop t!e node 545 its &lag is already 25 !ence it s!ould -e printed 54 2 .tep ".a 54 %+ "+ 5+ 2 .tep 5

%+ %+ "+ %+ 3

5+ "+ "+ "+ ;7<< "+ "+ %+

2 1 2 2 2 2 1

.tep ".a 5+ .tep 5 .tep "..tep ".c .tep ".d .tep 5 .tep ". a"+ .tep 5

T!e stac6 is e$pty5 -ut t!e poped node !as &lag 15 !ence it 'ill -e again pus!ed in t!e stac6 'it! &lag 25 !ence t!e stac6 e$pty condition 'ill not -e true. %+ 2 .tep ".%+ %+ 2 .tep ".c )) 1 .tep ".d %+ )) )) 1 .tep 2 (1 1 .tep 3 %+ )) (1 (1 1 .tep 2 (+ 1 .tep 3 %+ )) (1 (+ (+ 1 .tep 2 ;7<< .tep 3 %+ )) (1 (+ 1 .tep 5 (+ 2 .tep ".%+ )) (1 (+ (+ 2 .tep ".c ;7<< .tep ".d %+ )) (1 (+ 2 .tep 5 (+ 2 .tep ".a (+ %+ )) (1 1 .tep 5 (1 2 .tep ".%+ )) (1 (1 2 .tep ".c (4 1 .tep ".d %+ )) (1 (4 (4 1 .tep 2 ;7<< 2 .tep 3 %+ )) (1 (4 1 .tep 5 (4 2 .tep ".%+ )) (1 (4 (4 2 .tep ".c ;7<< .tep ".d %+ )) (1 (4 2 .tep 5 (4 2 .tep ".a (4 %+ )) (1 2 step 5 (1 2 .tep ".a (1 %+ )) 1 step 5 )) 2 .tep ".%+ )) )) 2 .tep ".c ;7<< .tep ".d

%+

.tep 5 .tep ".a )) 3 .tep 5 .tep ".a %+ .tep % .tep ( T!ere&ore t!e postorder tra*ersal is 445 525 545 5+5 "+5 (+5 (45 (15 ))5 %+. 7-1"-3- Inorder *raversa/ 0he inorder traversal of the tree is traversing the left subtree first, then root and then traversing the right subtree. i.e. -e&ore printing t!e node *alue5 print t!e *alue on ,H.. /onsider t!e treeC A A / 1 D B 8ig 11- Dinar *ree Processing orderC / A A &14DB QR recursi*e &unction &or tree tra*ersal inorder RQ *oid inSorder ( T, t ) L i& (t) L inSorder (tale&t)G QR *isit t!e le&t su-tree in inorder RQ print&(XYdT5 tadata)GQR *isit t!e node RQ inSorder (tarig!t)G QR *isit t!e rig!t su-tree in inorder RQ P P T!e iterati*e algorit!$ is as &ollo'sC

)) )) %+ %+

2 2 2 2

". .et te$p to root %. Pus! te$p (. .et te$p to te$pbs le&t ). i& te$p is not ;7<< t!en step 2. 1+. i& (stac6 is e$pty) t!en step 1+. 11. te$p M pop ( ) 12. print te$pEs data. 13. set te$p to te$pbs rig!t 14. step 4. 15. .top. e.g. In pre*ious tree %+ 'ill -e printed only a&ter "+5 "+ 'ill -e printed only a&ter 5+ 5+ 'ill -e printed only a&ter 44 44 does not !a*e le&t c!ild5 !ence 44 is printed. T!ere is no rig!t c!ild &or 445 !ence 5+ is printed As 'e $o*e to t!e rig!t o& 5+ i.e. 54 54 'ill -e printed only a&ter 52 52 does not !a*e le&t c!ild5 !ence 52 is printed. T!ere is no rig!t c!ild &or 525 !ence "+ is printed. T!ere id no rig!t c!ild &ir "+5 !ence %+ is printed. As 'e $o*e to'ards t!e rig!t c!ild o& %+5 i.e. )+5 )) 'ill -e printed only a&ter (1 (1 'ill -e printed only a&ter (+ (+ does not !a*e le&t c!ild5 !ence (+ is printed. T!ere is no rig!t c!ild &or (+5 !ence (4 is printed. As 'e $o*e to'ards t!e rig!t c!ild (1 i.e. (4 (4 does not !a*e le&t c!ild5 !ence (4 is printed. T!ere is no rig!t c!ild &or (45all nodes are printed. Hence t!e inorder tra*ersal is 4455+5525545"+5%+5(+5(15(45)) 8-ser*e t!at t!e inorder tra*ersal o& -inary searc! tree is al'ays t!e ascending order o& t!e data. 7-11- 8unctions to find Predecessor9 Successor9 Parent9 Drot)er

T!e &ollo'ing progra$ gi*es so$e use&ul &unctions. T!ese are also use&ul '!en 'e study Ainary T!readed Trees in t!e ne2t session. typede& struct tree QR structure o& t!e tree RQ L int dataG struct tree Rle&t5 Rrig!tG PRT,G T, !eadG QR !eader node RQ

T, getnode (*oid) QR creates ne' node and stores *alue into it RQ L T, te$pG int *alG te$pM$alloc(si eo&(struct tree))G te$p3W le&t M te$p3W rig!t M;7<<G scan&(cYdc5 :*al)G te$p3WdataM*alG return(te$p)G P *oid display (T, !ead) L Tr te$pG te$pM!eadG print&(cUnUtUtUtUt Ydc5 te$p3Wdata)G i&(te$p3Wle&t) L print&(cU-c)G display(te$p3W le&t)G P i&(te$p3Wrig!t) L print&(cUtUtc) display(te$p3Wrig!t)G P P

*oid createStree(*oid)G

QR 'e !a*e already seen t!is &unctionRQ

Tr searc!(T, root5 int target) QR searc! &or a node 'it! *alue targetRQ L do L i&(root3WdataMMtarget) QR '!et!er target is root RQ return(root)G else i&(target N root3Wdata) QR '!et!er it e2ists in le&t su-treeRQ L i&(root3W le&t) rootMroot3Wle&tG else return(;7<<)G P else L i& (root3Wrig!t) QR '!et!er it e2ists in rig!t su-treeRQ rootMroot3Wrig!tG else return (;7<<)G P P'!ile (1)G P T, parentS&ind(int target)QR to &ind t!e parent o& target RQ L T, te$p5 rootG root M !ead3W le&tG te$p M searc!(root5 target)G i&(te$pMM;7<<) QR node itsel& is not present) return(te$p)G else L i&(targetMM !ead3W le&t3Wdata) return(!ead)G

else L te$pM!ead3Wle&tG do L i&(target Nte$p3Wdata) L i&(targetMMte$p3Wle&t3Wdata) return(te$p) else te$pMte$p3Wle&tG P else L i&(targetMMte$p3W rig!t3Wdata) return(te$p)G else te$pMte$p3Wrig!tG P P'!ile(1)G P P P *oid parent(*oid) L T, resultG int *alC c!ar ans MbFb '!ile (ansMMbFb) L clrscr()G print&(c1nter node to &ind parentCc)G scan& (cYdc5 :*al)G result M parentS&ind(*al)G i&(resultMM;7<<) L print&(cUn ;ode is not in t!e tree ZUnc)G print& (c1nter node properlyZUnUnc)G getc!()G P else i&(resultMM!ead)

L print(cUnUn ;ode is t!e root. Un It !as no parentZc)G getc!()G P else L print&(XUn parent is YdZT5 result3Wdata)G getc!()G P print&(cUnUn /ontinue (yQn)c)G ans M toupper(getc!())G P P int -rot!erS&ind(int target) L T, root5 te$pG int &lagM+G root M !ead3W le&tG te$p M searc!(root5 target)G i&(te$pMM;7<<)QR '!en node itsel& is not presentRQ return(31)G else L i& (target MM!ead3W le&t3Wdata) return(3))))G else L te$pM!ead 3W le&tG do L i&(targetNte$p3Wle&t3Wdata) L i&(targetMMte$p3Wle&t3Wdata) L &lagM1G i&(te$p3Wrig!t) return(te$p3Wrig!t3Wdata)G else return(+)G P else

L i& (targetMMte$p3Wrig!t3Wdata) L &lagM1G i&(te$p3Wle&t) return(te$p3Wle&t3Wdata)G else return(+)G P else te$pMte$p3Wrig!tG P P'!ile(&lagMM+)G P P P *oid -rot!er(*oid) L int *al5 resultG c!ar ans MbFb '!ile (ansMMbFb) L clrscr()G print&(cUnUnUnc)G print&(c1nter node to &ind -rot!er Cc)G scan&(cYdc5 :*al)G result M -rot!erS&ind(*al)G i&(resultMM31) +L print&(cnode is not in t!e treeZUnc)G print&(X1nter node properlyZUnUnc)G P else i&(result MM3)))) L print& (cUnUn ;ode is t!e root. Un It !as no -rot!erZc)G getc!()G P else L i& (result MM+)

print& (cUn ;ode !as no -rot!er ZUnc)G else print&(cUn Arot!er is Yd Zc5 result)G getc!()G P print&cUnUn /ontinue (yQn)c)G ans M toupper(getc!())G P P Tr le&t$ost (T, node) L '!ile(node3W le&tZM ;7<<) nodeMnode3W le&tG return (node)G P T, rig!t$ost(T, node) L '!ile (node3Wrig!tZM;7<<) nodeMnode3Wrig!tG return(node)G P int successorS&ind(int target) L T, root5 te$p5 l$ost5 pG rootM!ead3Wle&tG te$pMsearc!(root5 target)G i&(te$pMM;7<<) QR'!en node itsel& is not presentRQ return(31)G else L i& (te$p3Wrig!t) L l$ostMle&t$ost(te$p3Wrig!t)G return(l$ost3W data)G P else L pMparentS&ind(te$p3Wdata)G '!ile(p3Wle&t ZMte$p)

L te$pMpG pMparentS&ind(te$p3Wdata)G P return (p3Wdata)G P P P *oid successor (*oid) L int succ5 targetG c!ar ans M bFbG clrscr( )G '!ile(ansMMbFb) L print&(cUn 1nter node to &ind successorc )G scan&(cYdc5 :target)G succMsuccessorS&ind(target)G i&(succMM31) L print&(c;ode is not in t!e treeUnc)G print& (c1nter node properly ZUnUnc)G P else i&(succMM3)))) L print& (cUnt!is node !as no successor Z Unc)G getc!()G P else L print& (c.uccessor is Ydc5 suc!)G getc!()G P print&(cUnUn /ontinue (yQn)c)G ans M toupper(getc!())G P P int predeccessorS&ind(int target) L

Tr root5 te$p5 r$ost5 pG rootM!ead3Wle&tG te$pMsearc!(root5 target)G i&(te$pMM;7<<) QR'!en node itsel& is not presentRQ return(31)G else L i& (te$p3Wle&t) L r$ostMrig!t$ost(te$p3Wle&t)G return(r$ost3Wdata)G P else L pMparentS&ind(te$p3Wdata)G '!ile(p3Wrig!tZMte$p :: dataZM 3)))) L te$pMpG pMparentS&ind(te$p3Wdata)G P i&(p3WdataMM3)))) return (3))))G else return(p3Wdata)G P P P *oid predeccessor (*oid) L int pred5 targetG c!ar ansMbFbG clrscr()G '!ile (ans MMbFb) L print&(cUn enter node ti &ind predeccessorCc)G scan&(cYdc5 :target)G predMpredeccessorS&ind(target)G i&(predMM31)) L print&(cUn ;ode itsel& is not present. Unc)G

print&(c1nter node properly ZUnUnUnc)G getc!()G P else i& (predMM3)))) L print&(cUn t!is node !as no predeccessorZ ;c)G getc!()G P else L print&(cPredeccessor is Ydc pred)G getc!()G P print&(cUnUn /ontinue (yQn)T)G ansMtpupper(getc!())G P P $ain() L createStree()G -rot!er( )G parent ( )G successor ( )G preedeccessor()G P 7-12- *o de/ete a node fro2 t)e tree .uppose &or so$e reason 'e are re@uired to delete a *alue &ro$ t!e tree5 t!en i& it is t!e lea& node t!ere 'ill not -e any di&&iculty in deleting t!e *alue. De 'ill !a*e to &ind t!e parent node o& t!at *alue and set t!e respecti*e pointer to ;7<<. Aut i& it is any ot!er node 'e $ust replace t!e deleted node 'it! anot!er node suc! t!at t!e positions o& ne' nodes satis&y t!e condition o& t!e -inary searc! tree. De 'ill &irst 'rite a general algorit!$ and t!en a detailed pseudo code. Fou $ay de*elop t!e pseudo code into a progra$. Algorit!$C 1. deter$ine t!e parent node o& t!e node $ar6ed &or deletion. 4or root no parent e2ists.

2. 3.

I& t!e node -eing deleted !as eit!er a le&t or rig!t e$pty su-tree t!en append t!e non e$pty su-tree to its parent and e2it. 8-tain t!e inorder successor o& t!e node to -e deleted. Append rig!t su-tree o& t!is to its grandparent. ,eplace t!e node to -e deleted -y its inorder successor node. Also5 t!e successor node is appended to t!e parent o& t!e node 9ust deleted.

Pseudo code Assu$ptionsC ] is in&o o& t!e node to -e deleted. PA,1;T address o& t!e parent o& t!e node to -e deleted. /7, address o& t!e node to -e deleted. P,1D5.7// pointers to &ind inorder successor o& /7,. ? address o& t!e node to -e attac!ed to PA,1;T D direction &ro$ parent node to /7, H1AD list !ead 487;D *aria-le indicating '!et!er node is &ound or not. 1. QR Initiali e RQ i& H1AD3Wlptr ZM H1AD QR no tree e2ists RQ /7, M H1AD3WlptrG PA,1;T M H1AD D M J<E else print&(X;8D1 ;8T 487;D X)G returnG 2. QR searc! &or t!e node $ar6ed &or deletion RQ 487;D M J&alseE D!ile( Z487;D :: /7, ZM ;7<<) L i& /7,3Wdata M ] 487;D M JtrueE else i& ] N /7,3Wdata QR -ranc! le&t RQ L PA,1;T M /7, /7, M /7,3Wlptr D M J<E P else L

PA,1;T M /7, /7, M /7,3Wrptr D M J,E P i& 487;D MM J&alseE print&(X;8D1 ;8T 487;D X)G returnG PQR end o& '!ile RQ 3. QR per&or$ t!e indicated deletion and restructure t!e tree RQ i&( /7,3Wlptr MM ;7<<) QR e$pty le&t su-tree RQ ?M /7,3Wrptr C;>D1 else L i&(/7,3Wrptr MM ;7<<) QR e$pty rig!t su-tree RQ C;>D2 ?M /7,3Wlptr else QR c!ec6 rig!t c!ild &or successor RQ L .7/ M /7,3Wrptr i& (.7/3Wlptr MM ;7<<) L .7/3Wlptr M /7,3Wlptr C;>D3 ? M .7/ P else QR searc! &or successor o& /7, R. L P,1D M /7,3Wrptr .7/ M P,1D3Wlptr D!ile( .7/3Wlptr ZM ;7<<) L P,1DM.7/ .7/ M P,1D3Wlptr P QR connect t!e successor RQ P,1D3Wlptr M .7/3Wrptr .7/3Wlptr M /7,3Wlptr .7/3Wrptr M /7,3Wrptr ? M .7/ P P P QR connect parent o& ] to its replace$ent RQ i& D M J<E

C;>D!

PA,1;T3Wlptr M ? else PA,1;T3Wrptr M ? return ;o' let us consider so$e diagra$s t!at depict us *arious conditions t!at can occur '!ile deleting a node &ro$ t!e tree. Condition 1? 62pt /eft su4treeC:, 4+ 4" 4% Defore De/etion 55 3+ 4" After De/etion 8ig 11- tree 4efore and after de/etion of a node 3it) no /eft su4tree Condition 2? 62pt rig)t su4treeC:, 4+ 3+ 5( Defore De/etion 55 55 "1 ") >ode to 4e de/eted A !" "1 5( ")
5

"1 5( ")

>ode to 4e de/eted A !"

3+ 5( After De/etion

"1 ")

8ig 12- tree 4efore and after de/etion of a node 3it) no rig)t su4tree Condition 3? Hit) rig)t su4tree55 4+ 21 4" 5% 5" "1 5( "+ C:, >ode to 4e de/eted A '1 "% %+

Defore De/etion 55 4+ 21 4" 5% 5" "% 5( "+ %+

After De/etion 8ig 13- tree 4efore and after de/etion of a node 3it) rig)t su4tree

Condition !? Hit) rig)t and /eft su4tree 4+ 2+ )+ 1(+ 2(+ 2)+ Defore De/etion 4+ 2+ )+ 1(+ 2)+ 1++ 2(+ 3++ 31+ 1++ C:, 2++ >ode to 4e de/eted 2"" 3++ 31+

After De/etion 8ig 1!- tree 4efore and after de/etion of a node 3it) 4ot) su4tree

All t!e arit!$etic e2pressions contain *aria-les or constants5 operators and parent!esis. T!ese e2pressions are nor$ally in t!e in&i2 &or$5 '!ere t!e operators separate t!e operands. Also5 t!ere 'ill -e rules &or t!e e*aluation o& t!e e2pressions and &or assigning t!e priorities to t!e operators. T!e e2pression a&ter e*aluation 'ill result in a single *alue. De can e*aluate an e2pression using t!e stac6s and e2pression trees. 7-13- 67pression *reesDe !a*e already seen !o' to sol*e e2pressions in &or$ o& post&i2 or pre&i2 &or$ 'it! t!e !elp o& stac6s. 12pressions can also -e sol*ed using tree called as e2pression trees. /onsider an in&i2 e2pressionC 2 O 3 R ( 4 " Q 2 O % ) Q (2 O 3) (4 1) R (2 1+ Q 2))

T!e e2pression tree &or t!is e2pression isC 3 O 2 R 3 3 4 Q " 2 O % 2 Q O 3 4 3 1 2 1+ Q 2 R 3

8ig 15-67pression tree

De can o-ser*e t!at an e2pression tree !as t!e operators in all roots and t!e operands are in lea*es o& t!e respecti*e operators. T!e e*aluations 'ill al'ays -eing &ro$ t!e -otto$ o& t!e tree5 i.e. "Q2 is t!e &irst operation5 '!ic! con&ir$s 'it! t!e usual procedure s!o'n a-o*e. A 'rong e2pression tree5 'ould result in 'rong ans'er. e.g. 4 2 3 3. T!e ans'er is 1. T!e e2pression trees could -e

3 4 2 3 3 4 3

3 3 2

T!e di&&erence in t!e trees is due to t!e associati*ity rules. In t!e &irst case5 233 'ill -e e*aluated &irst5 resulting in 1 and t!en it 'ill -e su-tracted &ro$ 4 resulting in 5. In t!e second case5 432 'ill -e e*aluated &irst5 resulting in 2 and a&ter su-tracting 35 'e get t!e ans'er as 1. Hence 'e can conclude t!at t!e second tree is proper. D!en it co$es to sol*ing t!e e2pression5 using co$puter5 t!e e2pression in t!e in&i2 &or$ 'ould -e slig!tly trou-leso$e5 or i& 'e $a6e certain con*ersions5 t!e e*aluations 'ill -e $uc! easier. T!ese &or$s are5 na$ely5 pre&i2 and post&i2 e2pressions. De 'ill see anot!er e2a$ple -y dra'ing t!e e2pression tree &or t!e &ollo'ing e2pression a % -( c R d Q a O a) R - O a T!e easiest 'ay &or e*aluation as 'ell as &or t!e ot!er purposes5 is to 'rite e2pression in &ully parent!esi ed &or$. During t!is process5 'e s!ould consider t!e steps &or e*aluation. a-3(cRdQaOa)R-Oa M a - 3 ( c R e 1O a ) R - O a M a - 3 ( e2 O a ) R - O a M a - e3 R - O a M a - 3 e4 O a M e" O a M e%

4or$ing t!e tree 'ill -e easy &ro$ any o& t!e a-o*e notations. Tra*el &ro$ -otto$ to root.

O e7A a

d e5

O 3

d a e4 a 3

O 3 e4 a

d O 3 3 a e3 R a

d 3 3 a e2 d O

O a R a O

3 3 a R c e1 O a R -

d 3 3 a R c Q O

O a R a

T!e ot!er 'ay o& generating t!e tree is to con*ert t!e e2pression to t!e &ully parent!esi ed &ro$. T!en e*ery ti$e you re$o*e t!e pair o& -rac6ets you 'ill get t'o operands separated -y an operator5 $a6e t!at operator5 t!e root and t!e t'o operands as le&t and rig!t c!ild and repeat t!e process. /on*ersion to t!e &ully parent!esi ed &or$ is s!o'n -elo'C a-3(cRdQaOa)R-Oa

Ma-3(cR(dQaOa)R-Oa Ma-3((cR(dQaOa))R-Oa M a - 3 ( ( ( c R ( d Q a ) ) O a ) R - O a M(a-)3(((cR(dQa))Oa)R-)Oa M ( ( a - ) 3 ( ( ( c R ( d Q a ) ) O a) R - ) ) O a M(((a-)3(((cR(dQa))Oa)R-))Oa) During e*aluation 'e 'ill !a*e to sol*e t!e inner $ost -rac6et &irst as its priority 'ill -e t!e !ig!est. Driting e15 e25 e35 etc is e@ui*alent to putting t!e -rac6ets5 '!ic! is as s!o'n -elo'. (((a-)3(((cR(dQa))Oa)R-))Oa e5 e1 e2 e3 e4 e" e%

67ercises? 1. 2. Drite a progra$ to create a ternary tree and t!en to tra*erse it using inorder tra*ersal. I& a -inary tree !as say JnE le*els5 '!at is t!e $a2i$u$ nu$-er o& nodes contained in it[ I& 'e are gi*en JnE *alues and 'e are re@uired to generate a -inary tree5 '!at could -e t!e $ini$u$ and t!e $a2i$u$ lengt! o& suc! tree[ a. Drite a &unction to c!ec6 '!et!er t!e gi*en t'o trees are identical.

3.

-. Drite a &unction to c!ec6 '!et!er t!e structure o& t!e t'o trees is identical.

Session 8 0rees (Part 2) During this session you will learn about: A. 8. 9. :. 2inary threaded tree. 5ow to create a binary threaded tree from an e$isting binary tree. 0hreading during creation. Garious traversals and threading.

8-1 Introduction In t!e pre*ious session on trees5 'e !a*e seen t!e creation o& trees and its tra*ersal in detail. In t!is c!apter5 'e 'ill study so$e ad*ance &unctions and operations on trees. De !a*e de&ined t!e predecessor and successor 'it! re&erence to inorder tra*ersal. Here5 'e 'ill see !o' to reac! t!e$ 'it!out tra*eling &ro$ t!e root eac! ti$e. <et us -egin our discussion 'it! -inary t!readed tree.

8-2- Dinar *)readed *ree De !a*e de&ined t!e tree as a connected grap! 'it!out a circuit5 i.e. t!ere can -e no pat! &ro$ t!e *erte2 to itsel&. 4or -inary searc! tree t!ere could -e $a2i$u$ t'o c!ildren per node and t!e inco$ing degree o& eac! node is 1 and t!e outgoing degree o& eac! node is $a2i$u$ 2. Hence 'e declare t!e structure &or t!e node in t!e tree as struct -inStree L int datG struct -inStree Rle&t5 Rrig!tG P ;o' '!ene*er 'e allocate t!e $e$ory5 it 'ill -e allocated considering t!e si e o& data as 'ell as t!e $e$ory re@uired to store t'o pointers. Aut 'e &ind t!at 'e 'ill !a*e nodes in t!e tree5 '!ic! 'ill !a*e eit!er one or no c!ildren. In case o& all suc! nodes5 '!ere it does not !a*e eit!er a le&t c!ild or a rig!t c!ild5 t!e respecti*e pointer5 le&t or rig!t5 'ill contain ;7<<.

I& a tree contains n nodes5 t!en as per t!e de&inition it 'ill !a*e (n 1) edges. ;o' e*ery node !as t'o pointers in it. Hence t!ere is a capacity to store 2 nd address a$ong n nodes. To &or$ t!ese 'e are using (n31) pointers. Hence in a tree o& n nodes t!ere 'ill -e (n O 1) pointers5 '!ic! are stored as ;7<< -ecause t!e respecti*e c!ildren do not e2ist. As a concept as 'ell as t!e de&inition5 t!is is correctly i$ple$ented. Aut '!en 'e consider di&&erent algorit!$s and i& 'e actually study t!e repetiti*e re@uire$ents o& di&&erent operations on trees5 'e 'ill &ind t!at i& 'e utili e t!ose (nO1) locations to store sa$e speci&ic node addresses5 t!en t!e algorit!$s 'ould -e &aster and e&&icient. Aut i& you store addresses in t!ese5 t!en t!ere 'ill -e n edges5 *iolating t!e de&inition o& t!e tree. .o 'e decide to put so$e $ar6ing on t!ese addresses or edges5 indicating t!at t!ese edges do not -elong to t!e tree. De !a*e seen in t!e trees5 t!at all t!e nodes 'ill point to t!eir descendent or c!ildren. Hence t!e direction o& all t!e edges is do'n'ards. T!e edges5 '!ic! 'e 'ill -e introducing5 eit!er point up'ards or at t!e sa$e le*el. 8nce t!is is decided5 t!en 'e &ind t!at 'e cannot decide '!et!er a particular node is a lea& node5 -ecause t!ere 'ill -e addresses in t!e positions le&t and rig!t. Aut no' 'e 'ould c!ec6 t!e $ar6ings on t!ee edges or '!at 'e 'ill -e calling as &lags5 s!ould -e c!ec6ed. T!ere 'ill -e t'o &lags per node5 l&lag &or le&t edge and r&lag &or rig!t edge. D!en t!ese &lags !a*e *alue 15 t!en 'e can say t!at t!e c!ildren are present. D!en l&lag is 1 and r&lag is +5 t!e node !as le&tson -ut it does not !a*e t!e rig!t son. D!en l&lag is 15 'e can say t!at t!e node !as le&t c!ild and its address 'ill -e stored at t!e le&t. Aut '!en l&lag is +5 in t!e le&t 'e 'ill get t!e address o& so$e ot!er node in t!e tree t!at is not t!e c!ild o& t!e original node. Actually l&lag M + !as pointed out t!at le&t c!ild is a-sent. T!ese addresses5 '!ic! 'e store in le&t or rig!t lin6s &or$ t!e edges5 '!ic! are not edges o& t!e tree. T!ese are 6no'n as J t)readsE. T!e tree t!us &or$ed is called as *)readed Dinar *ree. T!ere $ust -e so$e logic to decide as '!ere t!e le&t t!read or t!e rig!t t!read o& a particular node is pointing at. De can store t!ese addresses depending on a particular tra*ersal. 8-2-1- Inorder *)reading H)en t)e /eft t)read points to t)e inorder predecessor and rig)t t)read to inorder successor9 t)e t)reading is $no3n as IInorder *)readingGTo !a*e a t!readed -inary tree5 t!ere are t'o 'ay o& creation5

Fou can create a si$ple -inary tree and t!en t!read it. During creation only5 &or$ t!ese t!reads.

<et us consider t!e &irst one. 8-2-1-1- *o create a si2p/e 4inar tree and t)en t)read it De already 6no' !o' to create a -inary searc! tree. I& 'e 'ant to t!read t!is tree5 t!en 'e 'ill !a*e to per&or$ t'o 9o-s. To set t!e &lag to proper *alues and To set t!e proper addresses in place o& ;7<<.

Hence again 'e are re@uired to tra*el t!roug! all t!e nodes5 c!ec6ing &or t!e ;7<< pointers. T!is can -e done using Areadt! 4irst .earc!. T!roug! A4. '!en 'e get t!e node5 per&or$ t!e &ollo'ing steps. 1. .ay t!e node is te$p. 2. I& te$p !as le&tson5 set l&lag M1 1lse te$pEs le&t to point to its predecessor and set l&lag M + 3. I& te$p !as rig!tson5 set r &lag M 1 1lse te$pEs rig!t to pint to its successor and set r&lag M +. T!ere 'ill -e one node5 i.e. t!e le&t$ost5 '!ic! does not !a*e predecessor and one node5 i.e. t!e rig!t$ost5 '!ic! does not !a*e t!e successor. At t!ese places5 'e s!ould respecti*ely 'rite t!e address o& !eader. /onsider t!e -inary searc! tree &or$ed -y using. (. 2+ 2( 2% 42 1+ 3" 3( 3) 32 25 3% 5 i.e. ). 42 1+ 2% 25 2( 32 3%
3 0

3" 3( 3)

fig 1- Dinar tree T!e corresponding t!readed -inary tree 'ill -e Header 3+ 1+. 42 1+ 2% 25 2( 32 3% 3" 3( 3)

<e&t T!read C Inorder Predecessor ,ig!t T!read C Inorder .uccessor fig 2- Dinar t)readed tree for 4inar tree in fig 18-ser*e t!at pred (25) M215 succ (25) M 2% and t!e t!reads are indicating t!e sa$e nodes. T!us t!is 'ill !a*e *ery !ig! ti$e co$ple2ity as &or &inding t!e predecessor Q successor and t!en t!reading it.. To reduce t!e ti$e co$ple2ity5 'e can t!read t!e tree during creation only. 8-2-1 2- *o t)read t)e tree during creation It &ollo's a si$ple tec!ni@ue. Initially '!en t!e root is connected to t!e !eader5 it -eing t!e only node5 its le&t as 'ell rig!t t!reads are pointing to'ards t!e !eader. A&ter t!at '!ene*er 'e attac! a node to any ot!er node5 'e 'ill si$ply pull t!e e2isting t!read and generate a ne' t!read '!ere re@uired.

.uppose a node ne' is to -e attac!ed to te$p as le&tson5 t!en t!e &ollo'ing steps s!ould -e used. As ne' is attac!ed as le&tson o& te$p5 it 'ill -e in -et'een pred(te$p) and te$p. T!us t!e predecessor o& t!e te$p 'ill no' -e predecessor o& ne'. T!ere&ore ne' a le&t M te$p a le&t G te$p al&lag M 1 ne' a l&lag M + te$p ale&t M ne'

T!us 'e copy t!e t!read5 set proper *alues to &lags and attac! ne' as le&tson o& te$p. J;e'E is t!e lea& node. Hence 'ill e*en !a*e rig!t t!read pointing to t!e successor. Aut as ne' is le&tson o& te$p5 te$p 'ill -e successor o& ne'. T!ere&ore ne' a rig!t M te$p ne' a r&lag M + e.g. Header Header

3+ 21 fig 3- t)reading process

3+

.i$ilarly '!en ne' is to -e attac!ed as rig!tson o& te$p5 &ollo'ing steps 'ill -e used. T!us ne' a rig!t M te$p a rig!t (pull t!e t!read) te$p a r&lag M 1 ne' a r&lag M+ te$p a rig!t ne' ne' a let M te$p (parent 'ill -e predecessor) ne' a l&lag M +

Header

Header

3+ 21 2( 2% le&t t!read o& 2( is pulled -y 2% 2% ,ig!t t!read o& 3+ is pulled -y 42 fig !- t)reading process 21

3+ 42 2(

I& 'e $a6e t!e c!anges in t!e pre*ious create &unction5 'e can create t!e t!readed tree. <et us see a progra$ and understand t!e 'or6ing o& t!is tree creation process. K include Nstdio.!W K include Nalloc.!W K includeNconio.!W typede& struct tree L int dat5 l&lag5 r&lagG struct tree Rle&t5 Rrig!tG PRT,G T, @ue=2+>5 s5 !eaderG struct tree !eadG int &ront M+5 endM+5 T, pop()G *oid pus!(T, node)G int @ue$pty()G

int le&t$ost (T, te$p)G int rig!t$ost (T, te$p)G T, getnode (int *al)G *oid insert (T, ne')G *oid display()G $ain() L T, t5 ne'G c!ar cG int *alG !eader M $alloc(si eo&(struct tree))G !eaderadat M 1++++G print&(Xgi*e t!e data _T)G scan&(XYdT5 :*al)G s M getnode(*al)G !eader3Wle&t M sG s 3W le&t M !eaderG s3W rig!t M !eaderG do L print&(XBi*e t!e data _T)G scan&(XYdT5 :*al)G i& (*al ZM 3))) L ne' M getnode(*al)G insert (ne')G P P'!ile (*al ZM 3)))G display ()G P *oid insert (T, ne') L T, tG int &lag M +G t M slG '!ile (Z&lag) L i&(ne' 3Wdat Nt3Wdat) i& (t3Wl&lag) t M t 3W le&tG

else L ne' 3 W le&t M t 3W le&tG ne' 3Wrig!t MtG t 3 Wle&t M ne' G t 3 Wl&lag M 1G &lag M 1G P else i& (t3Wr&lag) t M t3Wrig!t G else L ne' 3W rig!t M t 3 W rig!tG ne' 3 W le&t M tG t 3 W r&lag M 1G t 3 W rig!t M ne' G &lag M 1G P P P T, getnode (int *al) L T, pG p M $alloc (si eo& (struct tree))E p3W l&lag M +G p3Wr&lag M+G p3WdatM*alG p3Wle&t M ;7<<G p3Wrig!t M ;7<<G return(p)G P *oid display() L int iM+5p5@G T, tG tMsG pus!(t)G pus! (:!ead)G print (Xt!e -readt! &irst searc! is _.UnT)G print&(X<101< YdC X5i)G

D!ile (Z@ue$pty()) L t M pop ()G i& (t MM :!ead) L i OOG print&(XUnKKKKKKKKKKK <101< I. 801, KKKKKUnT)G getc!()G print&(XUnUn <101< YdC X5i)G print&(UnZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZUnT)G pus! (:!ead)G P else L print&(X*alue is _.Y dUnT5 t3Wdat)G i& (t3Wl&lag) pMrig!t$ost(t3Wle&t)G else p M t3Wle&t3WdatG i& (t3Wr&lag) @Mle&t$ost (&t3Wrig!t)G else @Mt3Wrig!t 3WdatG print&(XPredecessor is Yd .uccessor is _YdUnT5p5@)G print(XUnRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRUnT)G P i&(t3Wl&lag) pus!(t3Wle&t)G i&(t3Wr&lag) pus!(t3Wrig!t)G P P T, pop() L T, nG n M @ue=&ront>G &ront OOG return(n)G P *oid pus! (T, no)

L @ue=end>MnoG end OOG P int @e$pty() L i& (&ront M M end31) return(1)G return(+)G P int rig!t$ost (T, te$p) L '!ile (te$p3Wr&lag) te$pMte$p3Wrig!tG return (te$p3Wdat)G P int le&t$ost (T, te$p) L '!ile(te$p3Wl&lag) te$pMte$p3Wle&tG return(te$p3Wdat)G P 8utput Bi*e t!e data _..5 Bi*e t!e data _..4 Bi*e t!e data _..% Bi*e t!e data _..) Bi*e t!e data _..3 Bi*e t!e data _..34 Bi*e t!e data _..12 Bi*e t!e data _..3)) T!e -readt! &ist searc! is _.. <101< + G *alue is _.5 Predecessor is _..4 .uccessor is __% RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR KKKKKKKKKKKKKKKKKK <101< I. 801, KKKKKKKKKKKKK

<101< 1 C ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ *alue is __4 Predecessor is ___3 .uccessor is _..5 RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR *alue is __% Predecessor is ___5 .uccessor is _..) RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR KKKKKKKKKKKKKKKKKKK <101< I. 801, KKKKKKKKKKKKKKKKKKKKKKKK <101< 2 C ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ 0alue is _..3 Predecessor is ____1++++ .uccessor is _..4 RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR *alue is __) Predecessor is ___% .uccessor is _..12 RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR KKKKKKKKKKKKKKKKKKKKKK <101< I. 801, KKKKKKKKKKKKKKKKKKKKK <101< 3 C ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ11 *alue is __34 Predecessor is ___12 .uccessor is _..1++++ RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR KKKKKKKKKKKKKKKK <101< I. 801, KKKKKKKKKKKKKKKKKKKKK <101< 4 C ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ *alue is __12 Predecessor is ___) .uccessor is _..34 RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR 8-3- Postorder *)reading In t!e Inorder t!reading 'e !a*e used t!e inorder t!reads5 i.e. '!en rig!tson 'as a-sent 'e !ad 'ritten t!e inorder successor at t!at position and &or le&tson5 i& a-sent 'e 'rite inorder predecessor. 4or postorder t!reading5 'e 'ill !a*e to place t!e postorder successor and postorder successor. To tra*el it in postorder5 &irst goto le&t$ost. I& it does not !a*e a rig!tson5 t!en print it. 1lse goto its rig!tson and its le&t$ost. (,epeat). D!en node does not !a*e rig!tson5 using t!read goto successor and print it. D!en 'e reac! a node5 '!ic! !as

rig!tson5 using t!read5 t!en print it and goto5 its parent and its rig!tson it repeat t!e process. T!e actual tra*ersal 'it! reasons is s!o'n -elo'. <et us see t!e postorder t!readed tree and t!e steps to see !o' it is done ne2tC

Header 3+ 21 1+ 2% 25 2( 32 3% fig 5- Post order Dinar t)readed tree 3" 3( 3) 42

*e2p

Print

1. Boto le&t$ost o& t!e root 2. /!ec6 '!et!er te$p !as rig!tson. I& yes5 te$p is te$pEs rig!t else print te$p and $o*e to rig!t t!read. /!ec6 '!et!er te$p !as rig!tson.

1+

1+ 25 25

2. I& yes5 te$p is te$pEs rig!t 1lse print te$p and $o*e to rig!t t!read. 2. /!ec6 '!et!er te$p !as rig!tson. I& yes5 te$p is te$pEs rig!t else print te$p and $o*e to rig!t t!read.

2% 2%

2. c!ec6 '!et!er te$p !as rig!tson. I& yes5 te$p is te$pEs rig!t else print te$p and $o*e to rig!t t!read. 3. ;o' 2+ is reac!ed t!roug! rig!t t!read !ence print it and $o*e its parent i& t!e pre*ious node 'as le&tson 4. #o*e to parents rig!t 1. Boto le&t$ost 2./!ec6 '!et!er te$p !as rig!tson. I& yes5 te$p is te$pEs rig!t else print te$p and $o*e to rig!t t!read. 2-c)ec$ 3)et)er te2p )as rig)tson- If es9 te2p is te2pJs rig)t e/se print te2p and 2ove to rig)t t)read2. /!ec6 '!et!er te$p !as rig!tson. I& yes5 te$p is te$pEs rig!t else print te$p and $o*e to rig!t t!read.

2( 2( 2+ 2+ 3+ 42 32

32 3%

3) 3)

2. c!ec6 '!et!er te$p !as rig!tson. I& yes5 te$p is te$pbs rig!t else print te$p and $o*e to rig!t t!read. 3. ;o' 3( is reac!ed t!roug! rig!t t!read !ence print it and $o*e its parent i& t!e pre*ious node 'as le&toson.

3(

3( 3"

4. T!e pre*ious node 'as rig!tson !ence again goto parent and print it. 2. /!ec6 '!et!er te$p !as rig!tson5 i& yes5 te$p is te$pbs rig!t else print te$p and $o*e to rig!t t!read. 3. ;o' 3+ is reac!ed t!roug! rig!t t!read !ence print it and $o*e its parent i& t!e pre*ious node 'as le&tson 4. D!en parent is !eader .T8P 8-!- Preorder *)reading

3" 42 42 3+ Header 3+

8n t!e si$ilar lines5 'e can t!read t!e tree using preorder t!reads. 4or preorder t!reading5 'e 'ill !a*e to place t!e preorder successor and preorder successor. 4or preorder tra*ersal a single tec!ni@ue can -e used. .tart &ro$ root5 $o*e to t!e le&t as long as le&tson e2ists. D!en l&lag is +5 $o*e to rig!t and repeat t!e process5 till 'e reac! t!e !eader. In all o& t!e a-o*e discussions5 'e &ind t!at inorder t!reading is *ery po'er&ul as 'e get t!e tra*ersals in -etter 'ay 'it!out calling t!e &unctions5 li6e parent. T!e preorder t!readed tree isC Header 3+

21 1+ 2% 25 2( 32 3% 3"

42

3( 3)

fig '- Pre order Dinar t)readed tree 8-5- *raversa/ of Dinar *)readed *ree 8-5-1? Inorder *raversa/ 4or an inorder t!readed -inary tree5 t!is tra*ersal 'ill -e *ery easy. I& 'e start &ro$ t!e le&t$ost5 t!en using rig!t t!reading 'e can get t!e inorder successor. Aut t!read is possi-le only '!en rig!tson is a-sent. D!en rig!tson is present. Its le&t$ost 'ill -e inorder successor. Hence t!e steps can -e 'ritten as &ollo's. 11. te$p M le&t$ost(root) 12. i& (te$p !as rig!tson) t!en te$p M le&t$ost(rig!tson) else te$p M te$p ` rig!t 13. repeat step 2 '!ile te$p Z M !eader Here 'e are $a6ing use o& le&t$ost &unction5 '!ic! returns t!e address o& t!e le&t$ost node o& t!e current $ode. T!us in pre*ious tree C Te$p M le&t$ost (3+) M 1+ Te$p does not !a*e rig!tson T!ere&ore using t!read te$p M te$pEs rig!t M 2+ Te$p !as rig!tson5 i.e.2( and t!e le&t$ost o& it 'ill -e 25 T!ere&ore te$p M le&t$ost (2() M 25 Te$p does not !a*e rig!tson5 t!ere&ore t!read. te$pM2( Te$p does not !a*e rig!tson5 t!ere&ore t!read. te$p M3+ Te$p !as rig!tson5 i.e. 425 '!ose le&t$ost is 32. And so on.

In preorder t!reading5 'e &ind t!at '!ene*er le&tson e2ists5 it 'ill -e t!e preorder successor and i& rig!tson is a-sent5 t!e rig!t t!read 'ill al'ays pint to t!e le&tson. D!ereas in postorder t!reading5 t!e tra*ersals 'ill contain parent &unction. 8-5-2- Preorder *raversa/ T!e preorder tra*ersal is ,oot <e&t ,ig!t. Here to tra*el le&t 'e do not re@uire any t!read5 !ence 'e can $o*e &ro$ root to its le&t$ost 9ust -y using <e&t c!ild. As 'e reac! t!e le&t$ost no' it is t!e ti$e to use t!read. T!e ne2t *alue to -e printed is t!e position i& 'e $o*e to rig!t 'it! t!read till 'e get t!e node !a*ing rig!tson. De $o*e to t!e rig!tson and again repeat t!e procedure. Hence t!e steps 'ill -e as &ollo's. g. te$p M root !. print te$pEs data i. i& (te$p ` l&lag is 1) t!en te$p M te$pEs le&t and goto step 2 9. else '!ile (te$p ` r&lag is +) te$p M te$p ` rig!t 6. te$p M te$p ` rig!t l. goto step 2 In case o& pre*ious tree C Initially te$p is 3+ Print 3+ ;o' te$p is 2+ Print 2+ ;o' te$p is 1+ Print 1+ ;o' te$p is 2+ ;o' te$p is 2( Print 2( ;o' te$p is 2% Print 2% ;o' te$p is 25 Print 25 ;o' te$p is 2% ;o' te$p is 2( ;o' te$p is 3+ ;o' te$p is 42 Print 42 ;o' te$p is 3" 3 step 1 3 step 2 3 step 3 3 step 2 3 step 3 3 step 2 3 step 4 3 step 5 3 step "Q2 3 step 3 3 step 2 3 step 3 3 step 2 3 step 4 3 step 4 3 step 4 3 step 5 3 step "Q2 3 step 3

Print 3" ;o' te$p is 32 Print 32 ;o' te$p is 3" ;o' te$p is 3( Print 3( ;o' te$p is 3% Print 3% ;o' te$p is 3( ;o' te$p is 3) Print 3) ;o' te$p is !eader 8-5-3- Postorder *raversa/

3 step 2 3 step 3 3 step 2 3 step 4 3 step 5 3 step "Q2 3 step 3 3 step 2 3 step 4 3 step 5 3 step "Q2 3 .T8P

4or postorder tra*ersal5 t!e printing se@uence 'ill -e <e&t ,ig!t ,oot. In t!is case 'e s!ould &irst goto t!e le&t$ost o& root5 t!en i& rig!tson e2ist5 t!en goto le&t$ost o& rig!tson5 else using t!read reac! a node5 '!ic! is inorder successor. /!ec6 '!et!er it !as rig!tson and repeat t!e process. ,e$e$-er '!ene*er 'e print a node '!ic! is -y itsel& a rig!tson5 t!en t!e ne2t $ode to -e printed is t!e le&t t!read o& its le&t$ost and t!en t!e ne2t node is rig!t t!read o& its rig!t$ost.

Potrebbero piacerti anche