Anda di halaman 1dari 348

rta:

HECKL ISTVN


ADATSTRUKTRK S
ALGORITMUSOK PLDATR

Egyetemi tananyag




































2011



































































COPYRIGHT: 20112016, Dr. Heckl Istvn, Pannon Egyetem Mszaki Informatikai Kar Rendszer- s
Szmtstudomnyi Tanszk

LEKTORLTA: Dr. Fbin Csaba, Kecskemti Fiskola Gpipari s Automatizlsi Mszaki Fiskolai Kar
Creative Commons NonCommercial-NoDerivs 3.0 (CC BY-NC-ND 3.0)
A szerz nevnek feltntetse mellett nem kereskedelmi cllal szabadon msolhat, terjeszthet,
megjelentethet s eladhat, de nem mdosthat.

TMOGATS:
Kszlt a TMOP-4.1.2-08/1/A-2009-0008 szm, Tananyagfejleszts mrnk informatikus,
programtervez informatikus s gazdasginformatikus kpzsekhez cm projekt keretben.




ISBN 978-963-279-506-5

KSZLT: a Typotex Kiad gondozsban
FELELS VEZET: Votisky Zsuzsa
AZ ELEKTRONIKUS KIADST ELKSZTETTE: Benk Mrta

KULCSSZAVAK:
adatstruktra, algoritmus, adatszerkezet, adattpus, bonyolultsg, programozs, feladatok, verem, sor, binris
fa, tmb
SSZEFOGLALS:
Az adatstruktrk s algoritmusok pldatr 146 feladat segtsgvel segti a hallgatk tudsnak elmlytst
az adott tmakrben. A pldatr elejn rvid ttekints tallhat a klnbz adatszerkezetekrl, az
algoritmusok tpusairl s bonyolultsgairl. A leggyakrabban hasznlt programozsi ttelek magyarzata is
fellelhet itt. A feladatok tpus szerint vannak csoportostva, pldul veremhez kapcsold feladatok, binris
keresfa feladatai, stb. A feladatok jelents rsze tbb alfeladatbl ll, amelyek sokszor nllan is
megoldhatak. Minden feladathoz megolds tartozik, amely a pldatr vgn tallhat, C illetve C++
nyelven. A pldatr az Adatstruktrk s algoritmusok kurzuson kvl hasznlhat programozs jelleg
trgyakhoz is.
Tartalomjegyzk 3
Heckl Istvn, PE www.tankonyvtar.hu
Tartalomjegyzk
Tartalomjegyzk ............................................................................................................... 3
1. Bevezets ...................................................................................................................... 7
1.1. Elmlet s gyakorlat ............................................................................................... 7
1.2. Kinek kszl a pldatr? ......................................................................................... 7
1.3. Az Adatstruktrk s algoritmusok jelentse ....................................................... 7
1.4. Az adatstruktra fogalma........................................................................................ 8
1.5. Az algoritmus fogalma ........................................................................................... 9
1.6. Hatkonysg ........................................................................................................... 9
1.7. A pldatr felptse ............................................................................................. 10
1.8. A fontosabb programozsi ttelek ......................................................................... 10
2. ltalnos feladatok ..................................................................................................... 13
2.1. Vizsgaeredmny ................................................................................................... 13
2.2. Sakktblarajzols.................................................................................................. 13
2.3. Terlet s kerletszmts..................................................................................... 13
2.4. Szmll ciklus .................................................................................................... 14
2.5. Sebessgmrs ..................................................................................................... 14
2.6. Adatbekrs ......................................................................................................... 14
2.7. Blokkon belli vltozk ....................................................................................... 14
2.8. Formzott kimenet ............................................................................................... 14
2.9. Hagyomnyos vagy norml forma ........................................................................ 15
2.10. Szorztbla ......................................................................................................... 15
2.11. Msodfok egyenlet ........................................................................................... 15
2.12. Opertorok ......................................................................................................... 15
2.13. Maszkols .......................................................................................................... 16
2.14. Hatvnysor ......................................................................................................... 16
2.15. Tpuskonverzi ................................................................................................... 16
2.16. DeMorgan .......................................................................................................... 16
2.17. Halmazllapot .................................................................................................... 17
2.18. Rmai szmok .................................................................................................... 17
2.19. Hromszg ......................................................................................................... 17
2.20. Ngyzet animci ............................................................................................... 18
2.21. Legnagyobb kzs oszt .................................................................................... 18
2.22. main paramterek ............................................................................................... 18
2.23. continue, break ................................................................................................... 18
2.24. Derivls ............................................................................................................ 18
2.25. Lpsenknti sszegzs ...................................................................................... 19
2.26. Alias vltozk .................................................................................................... 19
2.27. Kt kulcsos hozzfrs ....................................................................................... 19
2.28. Tbbszrs indirekci ........................................................................................ 19
2.29. Tpusvlaszts .................................................................................................... 20
2.30. Struktra kezels ................................................................................................ 20
2.31. Eskv ............................................................................................................... 20
2.32. Ventiltor ........................................................................................................... 20
2.33. Tbbszrsen sszetett tpus............................................................................... 21
4 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.34. Bitmezk ............................................................................................................ 21
2.35. Szbeli vizsga ..................................................................................................... 22
2.36. Csak olvashat fjl .............................................................................................. 22
2.37. tnevezs ........................................................................................................... 22
2.38. Szvegfjl ........................................................................................................... 22
2.39. Hamupipke ....................................................................................................... 22
2.40. XML ................................................................................................................... 23
2.41. Stopper ............................................................................................................... 23
2.42. Idpont formzsa ............................................................................................... 23
2.43. Tippels .............................................................................................................. 23
2.44. Milyen nap? ........................................................................................................ 24
2.45. Hrn kplet ....................................................................................................... 24
2.46. Hromszg .......................................................................................................... 24
2.47. Statikus adattag ................................................................................................... 24
2.48. Komplex szmok ................................................................................................ 24
2.49. Telefonszmla ..................................................................................................... 25
2.50. Halmazok metszete ............................................................................................. 25
2.51. Halmazok unija ................................................................................................. 26
2.52. Halmazok klnbsge ......................................................................................... 26
2.53. Binomilis ttel ................................................................................................... 27
2.54. Hazrdjtk ......................................................................................................... 28
2.55. Dtumellenrzs ................................................................................................. 28
2.56. Pascal hromszg ................................................................................................ 29
2.57. Lott ................................................................................................................... 30
2.58. Hanoi tornyai ...................................................................................................... 30
2.59. Trtek sszeadsa ............................................................................................... 31
2.60. Nevezetes szmok ............................................................................................... 32
3. Tmbk s mtrixok feladatai ...................................................................................... 34
3.1. Egy sztring cmei .................................................................................................. 34
3.2. Oszts s maradkkpzs ...................................................................................... 34
3.3. Sztring konvertls ............................................................................................... 34
3.4. Sztring bekrs ..................................................................................................... 34
3.5. Gykk ................................................................................................................. 35
3.6. Tmb reprezentlsa ............................................................................................. 35
3.7. Magassg mrs .................................................................................................... 35
3.8. Kockadobs .......................................................................................................... 35
3.9. Cssztats ............................................................................................................. 36
3.10. Mveletek tmbkn .......................................................................................... 36
3.11. Sztring talakts ................................................................................................. 36
3.12. Szveg statisztika ................................................................................................ 36
3.13. Kdolt beszd ..................................................................................................... 36
3.14. Sztring kivons ................................................................................................... 37
3.15. Kisbet - nagybet .............................................................................................. 37
3.16. Tmbnvels ...................................................................................................... 37
3.17. Mtrixszorzs...................................................................................................... 37
3.18. Virtulis memria ............................................................................................... 38
3.19. Gpels ............................................................................................................... 38
3.20. Nagy szmok sszeadsa .................................................................................... 38
Tartalomjegyzk 5
Heckl Istvn, PE www.tankonyvtar.hu
3.21. Medin ............................................................................................................... 38
3.22. sztndj ............................................................................................................ 39
3.23. Szavak keresse .................................................................................................. 40
3.24. Egyszer sztringfordt....................................................................................... 40
3.25. Riemann integrl ................................................................................................ 41
3.26. Polinomok sszeadsa ........................................................................................ 41
3.27. Caesar dekdol ................................................................................................. 42
3.28. CD katalgus ...................................................................................................... 42
3.29. Leltr.................................................................................................................. 43
3.30. Knyvtri rendszer ............................................................................................. 44
3.31. Kiklcsnztt knyvek ....................................................................................... 45
3.32. Sztr ................................................................................................................. 46
3.33. Sudoku ellenrz ................................................................................................ 47
3.34. Amba jtk ....................................................................................................... 47
3.35. Trkp ................................................................................................................ 48
3.36. Inverz mtrix ...................................................................................................... 49
3.37. Mtrixmveletek ................................................................................................ 50
3.38. Morze kd .......................................................................................................... 51
3.39. Mtrix szorzsa vektorral ................................................................................... 51
3.40. Sztring tokenizl ............................................................................................... 52
3.41. Szavak kicserlse .............................................................................................. 52
3.42. Ellenrz sszeg................................................................................................. 52
3.43. Statisztika ........................................................................................................... 53
3.44. Kerts ................................................................................................................ 53
3.45. Jegyek tlaga ...................................................................................................... 54
3.46. Nyltenyszts ................................................................................................... 54
3.47. Jegyek ................................................................................................................ 54
3.48. Marsjr ............................................................................................................. 54
3.49. Ritka vektor ........................................................................................................ 55
4. Lncolt listk feladatai ................................................................................................ 57
4.1. Lista kt tmbbel .................................................................................................. 57
4.2. Lista egy tmbbel ................................................................................................. 57
4.3. Lista szerkezet ...................................................................................................... 57
4.4. Lncolt lista dinamikus rekordokkal ..................................................................... 58
4.5. Sablon .................................................................................................................. 58
4.6. Lista ..................................................................................................................... 58
4.7. Prmszita .............................................................................................................. 59
4.8. Halmazmveletek ................................................................................................. 59
5. A verem s sor adatszerkezetek feladatai ..................................................................... 60
5.1. Verem osztly ...................................................................................................... 60
5.2. Verem .................................................................................................................. 60
5.3. Sor ....................................................................................................................... 60
5.4. Fordtott lengyelforma .......................................................................................... 60
5.5. Vrlista............................................................................................................... 61
5.6. Nyomtatk ........................................................................................................... 62
5.7. Pascal hromszg ................................................................................................. 62
5.8. Periodikus ads .................................................................................................... 62
5.9. Zrjelezs ........................................................................................................... 62
6 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
6. Binris fk feladatai ..................................................................................................... 63
6.1. Binris fa szlvel ................................................................................................ 63
6.2. Fabejrsok ........................................................................................................... 63
6.3. Binris keresfa .................................................................................................... 64
6.4. Csaldfa ................................................................................................................ 64
6.5. Matematikai kifejezsek kirtkelse .................................................................... 65
6.6.Binris fa feladatok ................................................................................................ 65
7. Grf feladatok .............................................................................................................. 66
7.1. Tzoltk ............................................................................................................... 66
7.2. Bolygkzi futrszolglat ..................................................................................... 66
7.3. Ozisok ................................................................................................................. 66
7.4. Srhlzat ............................................................................................................. 67
7.5. Pros grf.............................................................................................................. 67
7.6. Belmann-Ford algoritmus ..................................................................................... 67
7.7. Kruskal algoritmus ................................................................................................ 68
8. Rendezsi feladatok ..................................................................................................... 69
8.1.Tmbrendezs ........................................................................................................ 69
8.2. Rekurzv fggvnyek ............................................................................................ 69
8.3. Nvsor .................................................................................................................. 69
8.4. Rendezett lncolt lista ........................................................................................... 69
8.5. Kupacrendezs ...................................................................................................... 69
8.6. Szavak rendezse .................................................................................................. 70
8.7. Emlkeztetk ........................................................................................................ 70
9. Megoldsok ................................................................................................................. 72




1. Bevezets 7
Heckl Istvn, PE www.tankonyvtar.hu
1. Bevezets
1.1. Elmlet s gyakorlat
Az Adatstruktrk s algoritmusok trgy az informatika oktats egy fontos eleme, amely
elmlyti a programozs jelleg trgyak ismereteit azltal, hogy sorban megvizsglja a
gyakran hasznlt adatstruktrkat s a klnbz algoritmusokat. Fontos, hogy az elmleti
tuds mellett a hallgatk gyakorlati pldk megoldsa sorn szerezzenek tapasztalatot
arrl, hogy mikor, melyik algoritmus, milyen mdostssal alkalmazhat, annak megval-
stsnl, milyen nehzsgek merlhetnek fel. Ennek megfelelen a tmakr elmlett
trgyal jegyzet mellett elkszlt a jelen pldatr, amely szmos klnbz nehzsg
gyakorl feladatot tartalmaz.
1.2. Kinek kszl a pldatr?
A pldatr elssorban B.Sc. oktatsban rsztvev mszaki informatikusok, gazdasgi in-
formatikusok, programoz matematikusok szmra kszl, de elksztsekor igyekeztnk
gy eljrni, hogy a jegyzetet kzpiskolsok is minl hasznosabban hasznlhassk. Mint
korbban emltettk a pldatr az Adatstruktrk s algoritmusok elmleti jegyzetre pt
leginkbb. Azok hasznlhatjk leghasznosabban a jegyzetet s a pldatrat, akik mr ren-
delkeznek ltalnos informatikai ismeretekkel s tudnak alapszinten programozni. A pl-
dk megoldsa pszeud kdban, C-ben s C++ nyelven adottak. Az Adatstruktrk s al-
goritmusok szmos egyb trgynak, pldul a Szoftvertechnolginak, Opercis rend-
szereknek, Adatbzis-kezels elmlete, stb., az alapjt fogjk kpezni.
1.3. Az Adatstruktrk s algoritmusok jelentse
Adatstruktrk s algoritmusok alatt sokan, sokfle tmakrket rtenek. Vannak, akik
idesoroljk az sszes sszetett adatszerkezetet s a klasszikus programozs feladatok megol-
dst ler programozsi tteleket, mint az sszegzs, keress, eldnts, stb. Msok e trgy
alatt specilis terleteken megjelen, nagy bonyolultsg algoritmusokat rtenek, pldul
B-fk hasznlata, tmrtsi eljrsok, kdolsok, hash-technikk, stb. Ekkor a feladatok
gyakorlatban trtn implementlsa helyett, az elmleti httern van hangsly. Pldul
egy titkostsi algoritmus mkdsnek megrtse nem trivilis feladat. Azzal, hogy a tit-
kosts megfelel szint-e kln tudomnyterlet foglalkozik. Megint msok a trgy kere-
tben az algoritmusok bonyolultsgt, azaz tlagos s legrosszabb esetben trtn futsi
idejt s trignyt vizsgljk.
A mi megkzeltsnk az els rtelmezshez ll kzel, vagyis rintjk a hagyomnyos
programozsi tteleket, de bonyolultabb tmkat, pldul grf algoritmusok, is tekinteni
fogunk. Clunk, hogy egy alapszint programozsi ismeretekkel rendelkez hallgat, aki a
C nyelv szintaktikjt (vezrlsi szerkezetek, fggvnyek, mutatk, tmbk, struktrk)
ismeri, de akinek nincsen mlyebb programozsi mltja, az a pldatr feladatait megoldva
olyan igazi programozv vljon, aki magabiztosan hasznlja a klnfle algoritmusokat
s adatstruktrkat.
8 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
A feladatok szveges formban adottak, gy ahogy az els lps a feladat megrtse
kell, hogy legyen. Tapasztalataink szerint erre kln hangslyt kell fektetetni az oktats
sorn, klnben a hallgat nem tudja elkezdeni a feladatot, mert nem jn r, hogy a
megolds sorn melyik algoritmust kell alkalmazni, illetve nem rti, hogyan kell egy adott
adatstruktrt az adott feladathoz igaztani. Ezt a fajta tapasztalatot nem az elmlet tanul-
sval, hanem gyakorlatok megoldsval lehet megszerezni. Miutn valakinek kt-hrom
feladatnl kell a minimumkeress ttelt alkalmazni, ezutn remlhetleg minden knts-
ben felismeri a minimumkeressi feladatot s sztnsen hasznlja a r tanult megoldsi
mdszert. Ekkor mr magasabb absztrakcis szinten gondolkodik az illet, mivel az
sszegzst, kivlasztst, stb. rutinszeren tudja hasznlni, ezek vlnak szmra egy prog-
ram ptkvei, s nem az egyes vltozk s vezrlsi szerkezetek.
1.4. Az adatstruktra fogalma
Egy programon bell az adatokat vltozkban troljuk. Az egyszer adattpusok kt nagy
csoportra, egsz s lebegpontos vltozkra bonthatak. Mindegyik csoportban tbb tpus
tallhat, amelyek elssorban a trolhat rtkek rtkkszletben trnek el egymstl.
Pldul egy short int vltoz 2 bjton kisebb rtkkszlettel rendelkezik, mint a long int,
ami 4 bjtos (a legtbb 32 bites rendszerben).
A kt legfontosabb sszetett adattpus a tmb s a struktra. Az els sok ugyanolyan
tpus adatot fog ssze, amelyeket index alapjn lehet elrni. A msodik tbb, klnfle
tpus vltozt tartalmaz vltoz, ahol minden tagvltoz egyedi meznvvel rendel-
kezik. Sokszor az sem teljesen egyrtelm, hogy mikor rdemes ltrehozni hrom kln
vltozt s mikor egy hrom mezbl ll struktrt. Ha ezzel mr tisztban vagyunk,
akkor kvetkez lpcsfok, hogy az sszetett adattpusokat tovbb bonyoltsuk egymsba
gyazssal. Pldul egy tmb elemei lehetnek struktrk, amelynek az egyik mezje egy
msik struktra, amely tmbket is tartalmaz, stb.
Mutatk segtsgvel dinamikus adatszerkezeteket tudunk ltrehozni. Legegyszerbb
esetben a mutatkat hasznlhatjuk arra, hogy egy vltozt indirekt mdn, mutatja
segtsgvel rjk el. Akkor is mutatt hasznlunk, ha egy vltozrl nem tudjuk elre,
hogy biztosan szksg van-e r vagy egy tmb mrett nem ismerjk fordtsi idben.
Ekkor a memriafoglals csak akkor trtnik meg, amikor erre explicit utastst adunk. Ez
lehetsget ad arra, hogy pldul egy bekrt vltoz rtktl fggen hatrozzuk meg egy
tmb nagysgt. A mutatk legkifinomultabb hasznlata, amikor azok klnfle viszonyo-
kat jeleznek. Pldul egy lncolt listban a kvetkez elemet hatrozza meg a mutat, egy
binris keres fban pedig a szl s a gyerek elemeket.
Adatstruktrnak nevezzk a program adatait azzal az informcival egytt, hogy
azok milyen egyszer s sszetett adattpusokban troltak. Amikor adatstruktrrl besz-
lnk, akkor azokat az ltalnos struktrkat emltik elszr, amelyet legtbben hasznlnak,
mint a verem, sor, fa. Nem szabad elfelejteni, hogy a gyakorlatban leginkbb egyedi adat-
struktrkat hasznlunk, amelyek jval bonyolultabbak, mint egy egyszer lncolt lista.
Szintn fontos, hogy megrtsk a klnbsget az adattpus s az adatstruktra kztt.
Az adatstruktra magasabb absztrakcis szinten van, mint az adattpus. Egy adatstruktra
konkrt megvalstsa a programozsi nyelvtl fgg, de akr egy nyelven bell is tbb-
flekppen megvalsthatunk egy adott adatstruktrt. Pldul a binris fa lnyege, hogy
minden csompontnak legfeljebb kt gyereke lehet. Ezt az adatstruktrt megvalsthatjuk
1. Bevezets 9
Heckl Istvn, PE www.tankonyvtar.hu
mutatk segtsgvel, gy, hogy minden csompontot egy struktrval reprezentljuk,
amelynek van egy mezje, ami a bal, egy pedig, ami a jobb oldali csompontra mutat.
Ugyanez az adatstruktra tmbbel is megvalsthat. A tmb minden eleme egy rekord s
tudjuk, hogy a tmb i-dik elemnek a bal oldali gyereke az 2*i-dik elemnl, a jobb oldali
eleme pedig a 2*i+1-dik elemnl tallhat. Ha a fnak mondjuk, csak 3 szintje van, akkor
azt is megtehetjk, hogy felvesznk 7 darab kln vltozt, amelyek elnevezse utal arra,
hogy melyik csompontot reprezentljk. Teht egy darab adatstruktrt hrom klnfle
adattpussal lehet reprezentlni. Az llts visszafele is egy adattpussal klnfle adat-
struktrkat tudunk ltrehozni. Pldul tmb tpussal reprezentlhatunk, ft, sort, vermet.
1.5. Az algoritmus fogalma
Az algoritmus informlis megfogalmazsa szerint egy olyan utastssorozat, amelyet szisz-
tematikusan kvetve eljutunk egy adott feladat megoldshoz. Ez a definci impliciten
magba foglalja azt is, hogy csak olyan utasts sorozat tekinthet algoritmusnak, amely
vges szm lpsben megoldshoz vezet. A vgessg bebizonytsa sokszor nem trivilis
feladat.
A szmts illetve automata elmlet szerint a rekurzv nyelvekhez tartoz Turing g-
pek az algoritmusok. Az egyik Neumann elv kimondja, hogy a hardver s a szoftver egy-
msba tkonvertlhat, vagyis egy algoritmushoz tudunk konstrulni egy vele ekvivalens
Turing gpet s a Turing gphez fel tudjuk rni a neki megfelel algoritmust.
A pldatrban az algoritmus htkznapi defincijt tekintjk, amely szerint az algorit-
mus egy feladat megoldsnak rszletes lersa vagy mskppen utastsok s vezrlsi
szerkezetek. Fontos hangslyozni, hogy egy adott feladat megoldsra tbbfajta algoritmus
ltezhet. Ezek az algoritmusok klnbzhetnek, trignyben, sebessgben, a megvalsts
bonyolultsgban. Pldul egy rendezs algoritmus megvalsthat minimum kivlasztsos
mdszerrel quicksort s sok ms mdszerrel is. Mondhatjuk azt, hogy az algoritmus a
problma megoldsnak a megvalstsa. Ugyanakkor az algoritmus mg mindig egy
absztrakt lers, az ltala tartalmazott lpsek sokfle mdon, pldul klnbz progra-
mozsi nyelveken, valsthatak meg. Ilyen megkzeltsben egy program nem ms, mint
egy algoritmus konkrt implementlsa. Az implementls sorn is szmos krdsre kell
vlaszt adni. Pldul, ha egy halmaz elemein akarunk vgigmenni, akkor az alkalmazott
adatstruktrtl fgg, hogy el tudjuk-e kzvetlenl rni az elemeket, tudjuk-e, hogy
sszesen hny elem van, hogyan lehet meghatrozni a kvetkez elemet.
Az adatstruktra s az algoritmus egszet alkot, egyiket a msik nlkl megtervezni
nem lehet. ltalban az adatstruktra kialaktsval kezdjk a munkt, de az adatoknak s
a rajtuk vgezhet mveleteknek egytt van csak rtelme, ahogy ezt az objektum orientlt
programozs egyik elve is megfogalmazza.
1.6. Hatkonysg
Az elzekben megllaptottuk, hogy az adatoknl s az algoritmusoknl is tbb szint
ltezik, az elbbieknl az adatstruktra s az adattpus, az utbbinl az algoritmus s a
program szintje. Mindkt szinten felmerlnek krdsek, amelyek a hatkonysgot befoly-
soljk. A korbban emltett minimum kivlaszts rendezs n
2
-es, mg a quicksort n*log(n)
hatkonysg. Ha tudjuk, hogy osztlyban a tanulk szma 30-nl sose tbb, akkor rde-
10 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
mes tmbben trolni a hallgatkat, ha ellenben egyetemi vfolyamrl van sz, akkor egy
lncolt lista hatkonyabb lehet.
Egyltaln mirt szksges neknk hatkony kd, amikor a Moore trvny mg mindig
tartja magt, vagyis 18 havonta megduplzdnak a tranzisztorok szma a processzorokban
s a sebessgk tretlenl n. Egy mai telefon tudsa fellmlja egy 20 vvel ezeltti
szuperszmtgpt. Nem kne a hatkonysgnak, mint szempontnak httrbe szorulnia? A
vlasz nem. Ennek oka, hogy a szmtgpek fejldst bven leelzi az elvrsaink nve-
kedse. A megoldand feladatok egyre nagyobbak, sszetettebbek, sokrtebbek. Minden
programhoz ltezik olyan nagysg bemenet, amelyre a vgrehajtsi id mr percek vagy
akr napok. Teht fontos, hogy egy feladatot hatkonyan oldjunk meg, gy nagyobb mret
bemenetre is hasznlhat programot kapunk.
A hatkonysgra val trekvs kzben tartsuk szem eltt, hogy minden megolds ren-
delkezik elnykkel s htrnyokkal. Ha ltezne egyrtelmen legjobb megolds, akkor
mindenki azt hasznln. Pldul a legegyszerbb, gy leggyorsabban implementlhat, leg-
tlthatbb kd legtbbszr a leglassabb. Els vltozatnak, kismret bemenetek esetn
tkletes, de nagyobb inputok esetn a lasssg mr nem elfogadhat. Szintn kompro-
misszumot kell ktni a sebessg s a trigny kztt. Segdadatok szmolsval s trol-
sval a kd sebessge sokat javulhat, de erre egyre tbb trterletet kell ldozni. A megol-
ds hatkonysgt gy is nvelhetjk, hogy az eredeti feladatnak csak egy specilis esett
vizsgljuk, amelyre a feladat sajtossgait kihasznl kdot rhatunk. Ezutn viszont az
ltalnos esetet nem tudjuk kezelni.
1.7. A pldatr felptse
A bevezets utn a feladatokat nehzsg szerint prbltuk csoportostani. Tudjuk, hogy a
nehzsg fogalma viszonylagos, ez mgis valamilyen tmpontot adhat a hallgatknak. Egy
feladat nehzsge tbb tnyezbl addhat, ezek a feladat megfogalmazsa, a kd hossza,
az algoritmus illetve adatstruktra bonyolultsga, a szksges programozsi ismeretek. Egy
feladat sokszor tbb alfeladatbl ll. Az alfeladatok vagy sorban egymsra plnek vagy
egymstl fggetlenek, ekkor a kzs tma kapcsolja ket ssze. A feladatok megoldsai a
pldatr vgn helyezkednek el.
1.8. A fontosabb programozsi ttelek
A pldatr hasznlhatsgt nhny alapvet programozsi ttel megadsval szeretnnk
javtani. Ezek a ttelek, majd minden programban megtallhatak ilyen vagy olyan form-
ban. Ezek a ttelek tekinthetek a legfontosabb algoritmusoknak. Az itt lthat pszeud
kdokban az els tmb index az 1.
1.8.1. Megszmlls
A megszmlls algoritmusa megszmolja egy adott N elem sorozatban a T tulajdonsg
elemek elfordulsainak szmt. Ehhez szksgnk lesz egy vltozra, amiben a szmlls
eredmnyt troljuk. Az algoritmus pszeud kdja albb tallhat. Az algoritmus minden
esetben N lpst hajt vgre, azaz a bonyolultsga O(N).
A() // Az elemeket tartalmaz tmb
N // A tmb mrete
1. Bevezets 11
Heckl Istvn, PE www.tankonyvtar.hu
count := 0
ciklus i := 1-tl N-ig
ha A(i) T tulajdonsg akkor
count := count + 1
elgazs vge
ciklus vge
kir count
1.8.2. sszegzs
Az algoritmus sszegzi az N elem sorozat elemeit. A mkdse hasonlt a megszmlls
algoritmusra, azzal a klnbsggel, hogy most az sszeg vltozt nem egyesvel, hanem a
sorozat aktulis elemvel nveljk meg. Az algoritmus bonyolultsga szintn O(N).
A() // Az elemeket tartalmaz tmb
N // A tmb mrete
sum := 0
ciklus i := 1-tl N-ig
sum := sum + A(i)
ciklus vge
kir sum
1.8.3. Eldnts
Az algoritmus eldnti, hogy egy N elem sorozatban van-e legalbb egy T tulajdonsg
elem. A feladat a megszmlls algoritmussal is megoldhat, m annak az a htrnya, hogy
esetenknt feleslegesen dolgozik: Ha mr tallt egy T tulajdonsg elemet, akkor a tmb
tovbbi vizsglata felesleges. Mivel az algoritmus elindulsa eltt nem tudjuk, hogy
pontosan hny elemet kell megvizsglni, ezrt szmlls helyett ell tesztels ciklust kell
hasznlni. A ciklus megvizsglja, hogy az aktulis elem T tulajdonsg-e, valamint hogy
nem rtnk-e vgig a tmbn. Amennyiben elfogytak az elemek, vagy talltunk neknk
megfelelt, akkor a ciklus vget r, ellenkez esetben nveljk a tmb indexet s jabb
vizsglatot hajtunk vgre. Ha a ciklus utn az index rtke nagyobb lesz, mint N akkor, ha
nem talltunk T tulajdonsg elemet. Ha az index kisebb, vagy egyenl, mint az N, akkor
van legalbb egy T tulajdonsg elem a sorozatban.
A() // Az elemeket tartalmaz tmb.
N // A tmb mrete
index := 1
ciklus amg (index <= N) s (A(index) nem T tulajdonsg)
index := index + 1
ciklus vge
ha index <= N akkor
kir Van legalbb egy T tulajdonsg elem
egybknt
kir Nincs T tulajdonsg elem
elgazs vge

Fontos, hogy a ciklusfelttelben elbb szerepel az index <= N, mint az A(index) nem T
tulajdonsg felttel. Ellenkez esetben, ha a tmbben nincsen olyan elem, amit keresnk,
akkor az algoritmus ksrletet tesz a tmb utols utni elemnek a megvizsglsra, ami
hibt eredmnyez. Az algoritmus legjobb esetben 1, mg legrosszabb esetben pedig N l-
pst hajt vgre, gy a bonyolultsga O(N).
12 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
1.8.4. Szlsrtk meghatrozsa
Az algoritmus egy N elem sorozatban megkeresi a minimlis vagy maximlis elemet. Az
egyes elemeknek sszehasonlthatnak kell lennik. Tekintsk a minimlis elem keresst!
Vezessk be a min_index vltozt, amely az algoritmus lefutsa utn a minimlis elem
indext adja meg a sorozaton bell. Kezdetben min_index = 1, azaz ideiglenesen a sorozat
els elemt tekintjk minimlisnak. Azzal a felttelezssel lnk, hogy a tmb legalbb
egy elemet tartalmaz. Egy ciklussal vgigmegynk a sorozaton, s minden elemet sszeha-
sonltunk az aktulisan minimlisnak tekintett elemmel. Amennyiben tallunk olyan ele-
met, amely kisebb, mint a min_index-dik elem, akkor a min_index felveszi a kisebb elem
indext. Miutn vgignztk az elemeket, a min_index a legkisebb elem indext trolja.
Maximumkeressnl a klnbsg csupn annyi, hogy akkor a felttelben szerepl relcis
jel irnyt megfordtjuk. Az algoritmus bonyolultsga O(N).
A() // Az elemeket tartalmaz tmb
N // A tmb mrete
min_index := 1
ciklus i = 2-tl N-ig
ha A(i) < A(min_index)
min_index := i
ciklus vge
kir A legkisebb elem a min_index-edik: A(min_index)
1.8.5. Rendezs
Az algoritmus egy N elem sorozat elemeit nvekv sorrendbe lltja. Szmos rendez
algoritmus ltezik, itt a minimum kivlasztsos mdszert mutatjuk be. Felhasznljuk az
elz alfejezetben bemutatott szlsrtk meghatrozst azzal a kiterjesztssel, hogy meg-
adjuk azt is, hogy a tmb mely rsznek a minimumt keressk. A ciklus minden iterci-
jban meghatrozzuk a maradk, a mg nem rendezett, sorozat elemei kzl a legkisebbet
s ezt tesszk az aktulis vagyis az i-dik helyre. Az algoritmus bonyolultsga vletlenszer
inputra tlagos esetben O(N
2
), de pldul a gyorsrendezs tlagos bonyolultsga
O(n log(n)).
A() // Az elemeket tartalmaz tmb
N // A tmb mrete
ciklus i = 1-tl N-1-ig
mi := min_index_keress(A, i, n)
cserl(A(i), A(mi))
ciklus vge
kir A

2. ltalnos feladatok 13
Heckl Istvn, PE www.tankonyvtar.hu
2. ltalnos feladatok
2.1. Vizsgaeredmny
2.1.1. rjon programot, amely bekri egy vizsga eredmnynek szzalkos rtkt s
kirja, hogy sikeres volt-e a vizsga! A siker felttele az 50%-nl jobb teljest-
mny. tlet: gyeljen arra, hogy az 50% mg bukst jelent!
2.1.2. Krjen be pontszmot, amelynek -25 s 50 kz kell esnie! A vizsga sikeress-
gt csak akkor vizsglja, ha a pontszm a helyes intervallumban van! A siker
felttele a 25 pontnl jobb eredmny.
2.2. Sakktblarajzols
rjon programot, amely egy res sakktblt rajzol a karakteres kpernyre. A sakktbla
minden mezje kt egyms melletti szkzbl lljon! A mezk elvlasztsra hasznlja a '-'
s '|' karaktereket. Ksztsen fejlcet a sorok s az oszlopok szmra is, a soroknl szmo-
kat, az oszlopoknl betket hasznljon! A programot ksbb egy sakkprogram egyik kom-
ponense lesz.
2.2.1. A sakktbla elksztshez csak printf fggvnyt hasznljon a programban!
tlet: minden sorhoz kln printf-t hasznljon!
2.2.2. Az azonos sorok kirshoz hasznljon ciklust!
2.2.3. Egy adott sor kirajzolshoz is hasznljon ciklust! Keresse meg egy sor ismtl-
d mintjt s az kerljn a ciklus magjba! Figyeljen klnsen a fejlcek he-
lyes megjelentsre.
2.3. Terlet s kerletszmts
2.3.1. rjon programot, amely bekri egy tglalap kt oldalnak a hosszt, s hogy te-
rletet vagy kerletet akar-e a felhasznl szmolni! A vlasztstl fggen sz-
molja ki a terletet vagy a kerletet! Az oldal hosszak egsz rtkek, a vlaszts
karakter tpus. tlet: gyeljen arra, hogy negatv nagysg oldal nincsen!
2.3.2. Mdostsa az elz programot gy, hogy az oldalak hossza trt rtk is lehes-
sen! A program elejn krje be, hogy ngyzet vagy tglalapot vizsgl-e s ennek
fggvnyben krjen be egy vagy kt oldal hosszat!
2.3.3. Bvtse ki a programot gy, hogy az oldalak hossza csak pozitv rtk lehet, sk-
idomvlasztskor a kis s a nagy betket is fogadjuk el, ha rossz vlaszt adtunk,
akkor az jelezzk, vegyk be a vlaszthat idomok kz a szablyos hrom-
szget!
14 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.4. Szmll ciklus
2.4.1. rjon programot, amely kirja az egsz szmokat 0-tl 9-ig!
2.4.2. Mdostsa az elz programot gy, hogy 40-tl 60-ig fordtott sorrendben, a
pros szmokat rja ki! Az intervallum mindkt hatrt rja ki!
2.5. Sebessgmrs
2.5.1. Egymsba gyazott ciklusok segtsgvel hatrozza meg, hogy hny res ite-
rci tesz ki egy msodpercet, ha a ciklusvltoz egsz, illetve ha lebegpontos!
Minden ciklus 1000 lpst tegyen meg! Hny egymsba gyazott ciklus kell,
hogy a vgrehajtsi id 5-10 msodperc legyen?
2.5.2. Hatrozza meg az sszeads, szorzs, oszts, hatvnyozs idignyt gy, hogy
az elz program legbelsejbe berja a megfelel utastst!
2.6. Adatbekrs
2.6.1. rjon programot, amellyel bekri egy ember adati kzl a kvetkezket: azo-
nost szm - int, letkor - unsigned int, neme - char, slya - float, bankszmla
egyenlege - double, neve - char[200]! A bekrt adatokat rja ki jbl a
kpernyre! A megadott s a kirt rtk mikor klnbzhet? Mutasson r pldt!
2.6.2. Krje be majd rassa ki egy aut tulajdonsgait! A tulajdonsgok a kvetkezek:
mrka - char[200], vgsebessg - float, regisztrcis szm - hexa, tmeg -
double, tpus nv - char[300], utas szm - int, mholdas navigci - char.
2.7. Blokkon belli vltozk
2.7.1. Hozzon ltre egy olyan main fggvnyt, amelyben 3 klnbz tpus, 'a' nev
vltoz szerepel! Az egyes vltozk tpusai: const float, char [200], unsigned
long int. Ugyanolyan nev vltozkat egy fggvnyben bell gy tud ltrehozni,
hogy a vltoz definilsok klnbz blokkokban vannak. Egy negyedik vlto-
zba krje be, melyik blokkba menjen be a program, rassa ki az ott lv a vl-
toz rtkt!
2.8. Formzott kimenet
2.8.1. printf segtsgvel rja ki a kvetkez sorokat, gy hogy vltozkban trolja az
egyes rtkeket! A szkzt _-al jelljk. A kirand szveg:
_+12.45
_-234.1
+57967.2
+134567
2. ltalnos feladatok 15
Heckl Istvn, PE www.tankonyvtar.hu
2.8.2. Az elz feladathoz hasonlan rassuk ki a kvetkez sorokat:
_ _+235
_-1.291E4
00026
0XAB2
1.64e-003
2.9. Hagyomnyos vagy norml forma
2.9.1. rjon programot, amely t darab tmbben trolt float tpus szmrl krdezi
meg, hogy azt a printf %g-el trtn kirsakor hagyomnyos (f) vagy norml
(e) alakban jelenti meg! A szmot jelentsk meg elszr %f-el! rjuk ki a fel-
hasznlnak, hogy tippeljen, jelentsk meg a vlaszt %g-el, krdezzk meg,
hogy helyes volt-e a tipp! Szmoljuk a helyes vlaszokat!
2.9.2. Alaktsuk t a programot gy, hogy ne a tipp helyessgt krjk be, hanem
magt a tippet! Hasznljunk sprintf parancsot s hasznljuk ki azt, hogy norml
forma mindig tartalmaz egy 'e' bett. A program elejn krjk be a tmb
nagysgt, a program vgn, %-ban adjuk meg a helyes megoldsok szmt!
2.9.3. Alaktsuk t a programot gy, hogy minden iterciban krje be a %g-ben
hasznlt pontossgot is! A vlasz ne csak az legyen, hogy hagyomnyos vagy
norml formban trtnik a kirs, hanem pontosan meg kell adni szmot a
megfelel formban!
2.10. Szorztbla
2.10.1. Ksztsnk 5*5-s egyedi szorztblt, amelyet a karakteres kpernyn
jelentnk meg! Az els sor s oszlop rtkeit, amelyek mutatjk, hogy mit
mivel kell sszeszorozni, vonalakkal klntsk el a szorzatoktl! Az els sor s
az els oszlop rtkeit a billentyzetrl krjk be!
2.10.2. A szorztblhoz hasonl mdon valstsuk meg az egyedi sszead tblt! Az
els sor s az els oszlop rtkeit szveg fjlbl olvassuk be!
2.11. Msodfok egyenlet
2.11.1. rjon programot a msodfok egyenlet megoldsra! Elszr krje be az egytt-
hatkat, azutn rja ki, hogy hny megolds van s adja meg a megoldsokat!
2.11.2. Hatrozza meg a komplex gykket is! A komplex gykket is figyelembe vve
a msodfok egyenletnek mindig kt megoldsa van, de azok egybeeshetnek.
2.12. Opertorok
2.12.1. rjon programot a relcis opertorok mkdsnek a szemlltetsre! Krjen be
kt egsz vltozt s rja ki, hogy az egyes relcis opertorokat alkalmazva r-
juk milyen eredmnyt kapunk. Legyen lehetsg az elz lpsek ismtlsre!
16 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.12.2. rjon programot a logikai s bitenknti opertorok hasznlatnak a szemllte-
tsre!
2.13. Maszkols
2.13.1. Krjen be egy eljel nlkli karakter tpus vltozt egszknt s rja ki a kettes
szmrendszerbeli alakjt!
2.13.2. Krjen be egy szmot s az elz programmal rja ki a kettes szmrendszerbeli
alakjt! Krjen be egy bit pozcit s lltsa azt a bitet egyesre! rja ki az j rt-
ket tzes s kettes szmrendszerben is!
2.13.3. Folytassa az elz programot gy, hogy bekr mg kt bit pozcit! Az elsnl
trlje a bitet a msodiknl neglja. Minden rszeredmnyt rjon ki a kper-
nyre!
2.14. Hatvnysor
2.14.1. rjunk programot, amely hatvnysor s knyvtri fggvny segtsgvel is
kiszmolja e
x
rtkt a kvetkez kplettel: c
x
=
x
R
k!

k=0
Megfelelen pontos
rtket kapunk, ha a sort a negyedik elemig hatrozzuk meg. rjuk ki a hatvny-
sor s a vals rtk kztti klnbsget!
2.14.2. Krjnk be egy pontossgot s hatrozzuk meg, hogy a sor hny tagjt kell fi-
gyelembe venni, az adott pontossg elrshez!
2.14.3. Hatrozzuk meg a sin(x)-t hatvnysor segtsgvel!
2.15. Tpuskonverzi
2.15.1. rjon programot, amely bekr egy double rtket kirja az eredeti rtket a float,
int, short int, char tpuss konvertlt vltozatok nagysgt s rtkeit! A vlto-
zk mretei jobbra legyenek rendezve s az rtkek kirsa azonos oszlopban
kezddjn!
2.15.2. Hatrozza meg az eredeti s a konvertlt rtkek kztti klnbsgeket!
2.16. DeMorgan
2.16.1. rjon programot, amelyben egsz vltozkat hasznl logikaiknt! A vltozk a
kvetkezek: a - van pnzem, b - van kedvem, c - nincs idm, d - nagyon rde-
kel. Krje be a vltozk rtkeit s a kvetkezk alapjn dntse el, hogy megy-e
nyaralni: ha van pnze, kedve s ideje, akkor megy, ha az elzek kzl csak
egyik igaz, de nagyon rdekli akkor is megy. rja t a feltteleket DeMorgan
azonossgok segtsgvel!
2. ltalnos feladatok 17
Heckl Istvn, PE www.tankonyvtar.hu
2.16.2. Krje be a kvetkez vltozkat: a - esik az es, b - jnnek msok is, c - van
szabadnapom. Ezen vltozk alapjn hatrozzuk meg, hogy mikor megy a fel-
hasznl trzni. A felttelek a kvetkezek: akkor megyek trzni ha, nem esik
az es s van szabadnapom; akkor is trzom, ha msok nem jnnek, de az es
esik. rja t a feltteleket De Morgan azonossgok segtsgvel!
2.17. Halmazllapot
2.17.1. rjon programot, amely a vz hmrsklete alapjn megllaptja annak halmaz-
llapott!
2.17.2. Alaktsa t a programot, hogy ne Celsius fokot, hanem Farenheit-t kr be. Kln
fggvny vgezze el a konvertlst!
2.18. Rmai szmok
2.18.1. rjon programot, amely megadja, hogy mik a rmai szmjegyek (I, V, L, C, D,
M) arab megfeleli! Krjen be egy rmai szmjegyet, konvertlja nagybetre,
ha szksges s adja meg a szm rtket!
2.18.2. Ne csak egy darab szmjegyet, hanem egy tbb karakterbl ll szmot ala-
ktson t!
2.18.3. Valstsa meg a visszafele trtn konverzit!
2.19. Hromszg
2.19.1. Rajzoljon ki a karakteres kpernyre egy derkszg, egyenl szr hrom-
szget csillagokbl dupla for ciklus segtsgvel!

2.1. bra: Lehetsges kpernykp
2.19.2. Fordtsa el a hromszget gy, hogy a msik befog kerljn alulra!
18 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.20. Ngyzet animci
2.20.1. Ksztsen a karakteres kpernyn videt egy lees ngyzetrl! A ngyzet 3*3
csillagbl lljon! Miutn megjelentett egy kpet, vrjon rvid ideig, trlje a
kpernyt s jelentse meg a kvetkez kpet egy sorral lejjebb! Feltesszk,
hogy a karakteres kperny 80*25-s.
2.20.2. Mdostsa gy a programot, hogy amint a ngyzet eltnik alul, fell jelenjen
meg jbl!
2.20.3. Mdostsa gy a programot, hogy ngyzet helyett hromszg jelenjen meg, ami
alulrl pattanjon vissza!
2.20.4. Ngyzet helyett tglalap mozogjon vzszintesen a szlekrl visszapattanva!
2.21. Legnagyobb kzs oszt
2.21.1. rjon programot, amely kiszmolja kt szm legnagyobb kzs osztjt a
kvetkez algoritmus segtsgvel!
ciklus amg a kt szm nem egyenl
a nagyobb szm rtkt cskkentsk a kisebb szmmal

2.21.2. Mdostsa gy a programot, hogy az hrom szm legnagyobb kzs osztjt
szmolja ki!
2.22. main paramterek
2.22.1. rjon programot, amely kirja a program paramtereit fordtott sorrendben!
2.22.2. rja t gy a programot, hogy ell tesztels ciklust hasznl s a program nevt
nem rja ki!
2.23. continue, break
2.23.1. rjon programot, amely osztst vgez el egy htul tesztels ciklusban! Hasz-
nljon vgtelen ciklust, amelyet majd break paranccsal fog megszaktani! Krje
be a kt vltozt! Ha az osztand abszolt rtke nagyobb, mint 100, akkor hiba
zenet utn hajtsa vgre a kvetkez itercit! Ha az oszt rtke 0, akkor sza-
ktsa meg a ciklust! Szintn szaktsa meg a ciklust, ha mr hrom osztst elvg-
zett!
2.24. Derivls
2.24.1. rjon fggvnyt s hozz tartoz programot, amely a 3x
3
-2x
2
+6x-1 fggvnynek
megadja az 1., 2. vagy 3. derivltjnak az rtkt egy adott pontban! A fggvny
paramterei: hnyadik derivltrl van sz, milyen pontban tekintjk a derivltat.
A fggvny visszatrsi rtke: a derivlt rtke.
2. ltalnos feladatok 19
Heckl Istvn, PE www.tankonyvtar.hu
2.24.2. A sin(x) fggvnynek hatrozza meg az 1., 2. vagy 3. derivltjnak az rtkt
egy adott pontban! Hasznlja fel, hogy sin'(x) = cos(x), cos'(x) = -sin(x).
2.24.3. Tetszleges negyed-fok polinomnak hatrozza meg a derivltjt adott pontban!
Legyen a fggvnynek egy harmadik paramtere, ahol jelezzk, ha hiba trtnt,
vagyis ha az els paramter rtke helytelen, vagyis ngynl nagyobb!
2.25. Lpsenknti sszegzs
2.25.1. rjon programot, amely a konzolrl kr be egsz szmokat egy ciklus segts-
gvel s egy fggvny segtsgvel szmolja ki azok sszegt! Ezt a fggvnyt
minden szm bekrse utn hvja, ami ezutn visszaadja az eddigi szmok
sszegt. Hasznljon statikus vltozt a rszsszeg trolsra!
2.25.2. rjon olyan fggvnyt az elz programhoz, amely lenullzza az aktulis ssze-
get!
2.25.3. Mdostsa gy az elz programot, hogy nem hasznl statikus vltozt, hanem
paramterknt adja t az eddigi rszsszeget!
2.26. Alias vltozk
2.26.1. rjon programot, amelyben egy kocka fellett s trfogatt szmolja ki! gy
rja fel a kpletet, hogy kt ugyanolyan nev vltoz ne szerepeljen benne,
hanem hasznljon alias vltozkat mutatk segtsgvel.
2.26.2. Demonstrlja, hogy a * s a & ellenttes hats mveletek!
2.26.3. rjon az elzhz hasonl programot gmbre vonatkozan!
2.27. Kt kulcsos hozzfrs
2.27.1. rjon programot, amely egy titkos adatnak (vltoznak) a cmt egy mutatba s
egy egszbe kdolja gy, hogy a mutat s az egsz sszege a vltoz cmt
eredmnyezi! A program adja meg a kt adatot kt embernek egyenknt.
Ksbb krje be a mutatt s az egszet s ha ket sszeadva visszakapjuk a
vltoz cmt, akkor rja ki a vltoz rtkt.
2.28. Tbbszrs indirekci
2.28.1. rjon programot, amely a konzolos kpernyn szemlltet egy int*** mutatt s
az ltala mutatott rtkeket! rja ki a jelenlv vltozk cmt, rtkt s hogy
milyen alternatv mdon lehet hivatkozni a vltozkra!
20 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE


2.2. bra: Lehetsges kpernykp
2.28.2. rjon programot, amely a konzolos kpernyn szemlltet egy 2*3 dinamikus
double tmbt!
2.29. Tpusvlaszts
2.29.1. rjon programot, amelyben bekri, hogy rvid egsz vagy hossz lebegpontos
tpussal akar dolgozni. Hozzon ltre kt dinamikus vltozt a megfelel tpus-
bl! Krje be a vltozk rtkeit s az els vltoz rtkt nvelje meg a mso-
dikval!
2.30. Struktra kezels
2.30.1. Ksztsen struktrt, amely minden egyszer adattpusbl tartalmaz egyet vala-
mint egy egszre mutat mutatt! Krje be a struktra adattagjait a konzolrl,
majd rja ki azokat!
2.30.2. Mdostsa az elz programot gy, hogy ltrehoz j tpusnevet a struktrnak s
ezt hasznlja a tovbbiakban! Kln fggvnyben valstsa meg a struktra be-
kr s kir rszt! Hozzon ltre egy dinamikus struktrt, amit tegyen egyen-
lv a bekrt struktrval! Mdostsa a dinamikus struktrn keresztl az egsz
mutat ltal mutatott rtket!
2.31. Eskv
2.31.1. Ksztsen programot, amely tartalmazza a kvetkez adatszerkezeteket: ember
tpus: nv, letkor, azonost; gyr tpus: kart, rtk, kvek szma; eskv t-
pus: frj, felesg, eljegyzsi gyr, eskvi gyr, vendgek (dinamikus tmb),
vendgek szma. Inicializljon egy eskv tpus vltozt, rja ki a vltoz r-
tkt szpen trdelve gy, hogy minden struktra kirshoz kln fggvnyt hoz
ltre!
2.32. Ventiltor
2.32.1. rjon programot, amelyben ltrehoz egy ventiltor tpust: gyrt (statikus tmb),
termkszm, lers (dinamikus tmb), r! rjon fggvnyt, amely bekri az
2. ltalnos feladatok 21
Heckl Istvn, PE www.tankonyvtar.hu
adattagok rtkt s a rekordot visszatrsi rtkknt adja vissza! Szintn rjon
fggvnyt a struktra kirshoz!
2.32.2. Mdostsa gy a programot, hogy a ventiltor vltoz rtkt tegye egyenlv
egy msik vltozval, mdostsa az eredeti vltozban a gyrtt s a lerst!
rassa ki jbl mindkt struktrt! Milyen furcsasgot tapasztal? Hogy lehet azt
korriglni?
2.33. Tbbszrsen sszetett tpus
2.33.1. rjon programot, amelyben szemllteti a karakteres kpernyn a struktrk elhe-
lyezkedst a memriban! Hozzon ltre egy osztly tpus struktrt: hallgatk
szma, hallgatk Neptun kdjai (statikus sztring tmb), hallgatk pontszmai
(statikus lebegpontos tmb)! rjon fggvnyt, amely megjelenti a paramter-
knt tadott struktra adattagjainak a cmeit s rtkeit (a tmb tpus mezknek
csak az els elemt kell megjelenteni)! rja ki azt is, hogy milyen ms mdon
tud az adott cmre hivatkozni! Ezt az informcit is paramterknt adja t a kir
fggvnynek! Hozzon ltre ktelem tmbt osztly tpus struktrkbl!
Inicializlja a tmbt s hvja meg mindkt elemre a kir fggvnyt!

2.3. bra: Lehetsges kpernykp
2.34. Bitmezk
2.34.1. rjon programot egyn adatainak a trolshoz! Az ember tpus mezi a nv
(statikus tmb), nem, nagykor-e, csillagjegye, vallsa (5 nagy valls vagy
egyb), l szemly-e, vrcsoport, RH csoport! Hasznljon megfelel hossz
bitmezket! rjon bekr s kir fggvnyt, a kir fggvnynl ne szmokat,
hanem azok jelentseit rja ki! Hatrozza meg a struktra mrett!
2.34.2. Mdostsa gy a struktrt, hogy bitmezk helyett egsz vltozkat hasznl!
Mennyivel n a struktra mrete?
22 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.35. Szbeli vizsga
2.35.1. rjon programot, amelyben bekri egy szbeli vizsga minstst! A minsts
lehet: szrny, rossz, gyenge, j, kivl. Hasznljon felsorols tpust! rjon
fggvnyt a minsts szveges kirsra! Krje be az ismtl vizsga ered-
mnyt, hatrozza meg, hogy javtott-e az illet!
2.35.2. Oldja meg az eredeti feladatot #define-ok segtsgvel! Vezesse be a kzepes
minstst! Mirt jobb felsorols tpust hasznlni define helyett?
2.36. Csak olvashat fjl
2.36.1. rjon programot, amely belltja egy fjl csak olvashat tulajdonsgt! Krje
be egy szveges fjl nevt! lltsa be a fjl csak olvashat tulajdonsgt, majd
prbljon meg a fjl vghez fzni egy szveget C-bl hvott DOS parancs
segtsgvel (DOS parancs: echo text >>fileName)! Futtassa a DOS parancsot
C-bl: system(char*) segtsgvel! Trlje a csak olvashat tulajdonsgot s
prbljon ismt a fjl vghez fzni egy szveget!
2.36.2. rja meg a tuti trls programot! A program elszr trli a csak olvashat tulaj-
donsgot s utna DOS parancs segtsgvel trli a fjlt.
2.37. tnevezs
2.37.1. Feladat: rjon programot fjlok tnevezsre! A rgi s az j fjlnv a program
paramterben legyen adott! Ha valamelyik paramter hinyzik, akkor rja ki a
helyes hasznlatot! Ha hiba trtnik tnevezs kzben, akkor rja ki a megfelel
hibazenetet a hibakd alapjn!
2.38. Szvegfjl
2.38.1. rjon programot, amely bekri a kvetkez informcikat: minimlis rtk,
maximlis rtk fjl nv, adatok szma! Generljon adott szm vletlen szmot
a megfelel hatrok kztt s mentse el azokat egy szvegfjlba kln sorokba!
2.38.2. Mdostsa gy a programot, hogy az els sorba rja ki az adatok szmt! Szk-
zkkel vlassza el az egyes rtkeket s minden szmot fix hosszan rjon ki! 100
szmonknt szrjon be egy res sort!
2.39. Hamupipke
2.39.1. rjon programot, amely egy mr meglv, vletlen szmokat tartalmaz fjlban
lv szmokat sztvlogatja prossg alapjn! A pros s pratlan szmokat
trolja kln fjlokban! rjon fggvnyt, amely kiszmolja az egy fjlban lv
szmok tlagt! Alkalmazza a fggvnyt a kt fjlra s hatrozza meg a kt
fjlban lv szmok mennyisgnek az arnyt!
2. ltalnos feladatok 23
Heckl Istvn, PE www.tankonyvtar.hu
2.40. XML
2.40.1. rjon programot, amely XML-ben ment el rekordokat! A kocsi tpus azonostt
s rat, a szemly tpus nevet, letkort, a kocsik szmt, s kocsi tmbt
tartalmaz. Hozzon ltre s inicializljon egy 3 hossz szemly tmbt s mentse
el azokat XML fjlba! Az XML fjl legyen szpen trdelve! rjon halfTag s
fullTag fggvnyeket! Az elbbi csak <tagName> vagy </tagName> -t r
ki, az tbbi <tagName> Text </tagName>-t r ki.
Plda:
<Person>
<Name>Jani</Name>
<Age>22</Age>
<Count>3</ Count>
<Car>
<ID>0</ID>
<price>50.000000</price>
</Car>
<Car>


2.40.2. Mdostsa gy az XML fjlt, hogy Car tag-k egy Cars tag-on bell legyenek!
Ahol lehet, az adatok a tagok tulajdonsgaiban szerepeljenek! Pldul: <name
value="Jani"/>
2.40.3. Ksztsen beolvas programot! Jelezze ki az XML fjl szintaktikai hibit!
Pldul hibs tag, nyit tag prja hinyzik vagy fordtva, kt tag pr keresztben
van.
2.41. Stopper
2.41.1. Ksztsnk stopperrt, amely a program indtstl eltelt idt rja ki folyamato-
san! A program 11 msodperc utn lljon meg!
2.41.2. Mdostsa a programot gy, hogy csak minden egsz msodpercben rja ki az
eltelt idt!
2.42. Idpont formzsa
2.42.1. rjon programot, amely 10 msodpercen keresztl folytonosan kirja az aktulis
idt ezredmsodperc pontossggal! Hasznlja az _ftime s ctime fggvnyeket!
2.43. Tippels
2.43.1. rjon idtippel programot! A program lltson el egy vletlen szmot 1 s 5
kztt s ezt rja ki a kpernyre! Ennyi idt kell majd vrni a felhasznlnak.
24 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Ezutn krjen be kt sztringet gy, hogy mri a bekrsek kztt eltelt idt! rja
ki, hogy tnylegesen mennyi id telt el a kt bekrs kztt! Ha a bemenet a
quit sztring, akkor lpjen ki a programbl!
2.44. Milyen nap?
2.44.1. rjon programot, amely vletlenszeren meghatroz egy vet, hnapot, napot s
utna tippelni kell, hogy az a ht illetve v napjai kzl a hnyadik! Adja meg
hogy helyesek voltak-e a tippek!
2.45. Hrn kplet
2.45.1. rjon fggvnyt, amely a Hrn kplet segtsgvel kiszmolja a hromszg te-
rlett! Dobjon float tpus kivtelt, ha valamelyik oldal vltoz negatv s dob-
jon const char* tpus kivtelt, ha nem teljesl a hromszg egyenltlensg! A
kivteleket kezelje a main fggvnyben!
2.46. Hromszg
2.46.1. Ksztsen derkszg hromszg osztlyt, amelyben az adattagok az oldalak!
rja meg a set s get fggvnyeket az adattagokra! rja meg az area, perimeter,
check (ellenrzi, hogy tnyleg derkszg-e a hromszg) s display (kirja az
oldalak hosszt) fggvnyeket!
2.46.2. Ksztsen hasonl osztlyt egyenl szr hromszgre!
2.46.3. Ksztsen hasonl osztlyt szablyos hromszgre!
2.47. Statikus adattag
2.47.1. Ksztsen osztlyt, amelynek segtsgvel fjlba tud rni sorokat! A fjlnevet
tudjuk belltani objektumonknt s statikus adattag szmolja a program ltal
eddig kirt sorok szmt! Lehessen ezt az adattagot lenullzni s lekrdezni!
2.47.2. Mdostsa az elz programot gy, hogy szmolja a szavak s karakterek
szmt is!
2.48. Komplex szmok
2.48.1. rjon komplex szm osztlyt! Hasznljon privt adattagokat! rja meg az add,
sub, mul, div metdusokat! Az emltett metdusok rjk ki a mveletek eredm-
nyt a kpernyre!
2.48.2. Mdostsa gy a programot, hogy a metdusok ne vgezzenek kirst, hanem
adjk vissza az eredmnyt objektumknt! Valstsa meg kir opertort a komp-
lex osztlyra!
2.48.3. Valstsa meg az aritmetikai fggvnyeket opertorok segtsgvel!
2. ltalnos feladatok 25
Heckl Istvn, PE www.tankonyvtar.hu
2.49. Telefonszmla
2.49.1. rjon programot egy telefontrsasg szmra, ami az egyes elfizetk telefon-
szmlit szeretn kiszmolni! Az elfizetk adatai az in.txt nev fjlban trol-
ja! A program ksztsen felsorolst minden elfizet szmra, amelynek tartal-
maznia kell a teljes beszlgetsi idt, s a fizetend sszeget! Ezutn a program
szmolja ki, melyik elfizet telefonlt sszesen a legtbb ideig, ez milyen
hossz id, kinek kell a legtbbet fizetni, s mennyit! Hasznljon dinamikus
tmbket! Felttelezzk, hogy a bemeneti fjl az elrsoknak megfelel.
Az input formtuma:
Els sor: az elfizetk szma
Msodik sor: kt tzes szmrendszerbeli szm, a cscsidben val telefonls tarifja, s a
cscsidn kvli telefonls tarifja.
A tbbi sor az elfizetk adatait trolja: az elfizet neve (keresztnv, vezetknv), majd
kt tzes szmrendszerbeli szm: mennyi idt telefonlt az illet cscsidben, illetve
cscsidn kvl. Mind a keresztnv, mind a vezetknv maximum 10 karakterbl ll.
Plda bemenet:
2 // kt elfizet van
3 1 // a hvsdj 3 Ft/perc cscsidben, s 1 Ft/perc
cscsidn kvl
Bela Kovacs 731 123 // Kovcs Bla 731 percet telefonlt cscsidben, s
123 percet cscsidn kvl

Mihaly Toth 300 35
Kimenet:
Bela Kovacs: 2316 Ft 854 minute
Mihaly Toth: 935 Ft 335 minute

Highest fee: 2316 Ft
Bela Kovacs
Longest speaking: 854 Ft
Bela Kovacs
2.50. Halmazok metszete
2.50.1. rjon programot, amely kt halmaz metszett generlja! Mindkt halmaz egsz
szmokat tartalmaz. A program olvassa be az input fjlt! Krjen be egy szmot a
billentyzetrl, s dntse el, hogy a szm eleme-e az els halmaznak, a msodik
halmaznak, illetve ezek metszetnek! rassa ki a kpernyre az elbbi hrom
halmazt! Vgl rassa ki, hogy az els halmaz rszhalmaza-e a msodiknak,
illetve fordtva! Hasznljon dinamikus tmbket!
Az input fjl formtuma:
Els sor: az els halmaz mrete
Msodik sor: az els halmaz elemei
Harmadik sor: a msodik halmaz mrete
Negyedik sor: a msodik halmaz elemei
A szmok egy-egy szkz karakterrel vannak elvlasztva.
26 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Plda bemenet:
3
80 54 41
5
41 21 54 76 80
Kimenet:
Type a number: 76
76 is not element of A
76 is element of B
76 is not element of intersection of A and B
A = {80, 54, 41}
B = {41, 21, 54, 76, 80}
Intersection of A and B = {41, 54, 80}
B is not subset of A
A is subset of B
2.51. Halmazok unija
2.51.1. rjon programot, amely kt halmaz unijt generlja! Mindkt halmaz egsz
szmokat tartalmaz! A program olvassa be az input fjlt. Krjen be egy szmot a
billentyzetrl, s dntse el, hogy a szm eleme-e az els halmaznak, a msodik
halmaznak, illetve ezek unijnak! rassa ki a kpernyre az elbbi hrom
halmazt! Vgl rassa ki, hogy az els halmaz rszhalmaza-e a msodiknak,
illetve fordtva! Hasznljon dinamikus tmbket!
Az input fjl formtuma:
Els sor: az els halmaz mrete
Msodik sor: az els halmaz elemei
Harmadik sor: a msodik halmaz mrete
Negyedik sor: a msodik halmaz elemei
A szmok egy-egy space karakterrel vannak elvlasztva.
Plda bemenet:
3
80 54 41
5
41 21 54 76 80
Kimenet:
Type a number: 76
76 is not element of A
76 is element of B
76 is element of union of A and B
A = {80, 54, 41}
B = {41, 21, 54, 76, 80}
Union of A and B = {41, 21, 54, 76, 80}
B is not subset of A
A is subset of B
2.52. Halmazok klnbsge
2.52.1. rjon programot, amely kt halmaz klnbsgt generlja! Mindkt halmaz
egsz szmokat tartalmaz. A program olvassa be az input fjlt! Krjen be egy
2. ltalnos feladatok 27
Heckl Istvn, PE www.tankonyvtar.hu
szmot a billentyzetrl, s dntse el, hogy a szm eleme-e az els halmaznak, a
msodik halmaznak, az A\B vagy a B\A halmaznak! rassa ki a kpernyre az
elbbi ngy halmazt! Vgl rassa ki, hogy az els halmaz rszhalmaza-e a
msodiknak, illetve fordtva! Hasznljon dinamikus tmbket!
Az input fjl formtuma:
Els sor: az els halmaz mrete
Msodik sor: az els halmaz elemei
Harmadik sor: a msodik halmaz mrete
Negyedik sor: a msodik halmaz elemei
A szmok egy-egy szkz karakterrel vannak elvlasztva.
Plda bemenet:
3
80 54 41
5
41 21 54 76 80
Kimenet:
Type a number: 76
76 is not element of A
76 is element of B
76 is not element of A \ B
76 is element of B \ A
A = {80, 54, 41}
B = {41, 21, 54, 76, 80}
Set difference A\B = {}
Set difference B\A = {21, 76}
B is not subset of A
A is subset of B
2.53. Binomilis ttel
2.53.1. rjon programot, amely beolvas egy n rtket a billentyzetrl, majd a
binomilis ttel jobb oldalnak kifejtett alakjt kirja a kpernyre! n ne legyen
nagyobb 10-nl! A binomilis ttel szerint:
(a + b)
n
=
ahol n pozitv egsz szm, s (a + b)
n
=

Plda bemenet:
n=3
Kimenet:
( a + b )^3 = a^3 + 3ba^2 + 3b^2a + b^3
28 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.54. Hazrdjtk
2.54.1. rjon hazrdjtkot! A szablyok a kvetkezk: A jtk kezdetekor a jtkosnak
1000 Ft-ja van. A program generl egy vletlen szmot, a jtkosnak pedig meg
kell adnia egy tippet, s egy ttet. Ha eltallja a szmot, megkapja a tt sszegt,
ha nem, elveszti. Ezutn a program megkrdezi: Try again? (y/n), a jtkos-
nak pedig egy y vagy egy n karakterrel kell vlaszolnia. Ha jbl prblko-
zik, akkor a program j szmot generl. A jtk addig folytatdik, amg a jt-
kosnak van pnze, vagy amg nem szeretn befejezni a jtkot. 3 klnbz
szint van: a knny, amelyben a program 1 s 5 kztti szmot generl, a k-
zepes, amelyben 1 s 10 kztti szmot generl, s a nehz, amelyben 1 s
15 kztti szmot generl. A szintet a jtk megkezdse eltt vlasztja ki a jt-
kos, egy egyszer men segtsgvel. A jtk vgn a program rja ki a kper-
nyre, mennyit nyert vagy vesztett a jtkos.
Plda jtk:
Choose the difficulty!

Easy:...........1
Medium:.........2
Hard:...........3

2

You have 1000 HUF now.
Take your stake: 10
What's your tip (1..10)? 5
You've hit the number!
You have 1010 HUF!
Try again? (y/n)
y

Take your stake: 1000
What's your tip (1..10)? 1
The number was 7
You have 10 HUF!
Try again? (y/n)
n

Congratulations!
You get 10 HUF!
2.55. Dtumellenrzs
2.55.1. rjon programot, amely beolvas egy dtumot egy fjlbl, szintaktikai s
szemantikai ellenrzst vgez rajta s kirja az esetleges hibkat! Szintaktikai
ellenrzs: A dtum 3 szmot tartalmaz, mindegyik szm utn egy pont
szerepel. A szmok csak szmjegyet tartalmazhatnak! Pldul a 2007.
megfelel, de a kvetkezk nem: 2A07., 2007. Szemantikai ellenrzs:
Akkor hajtdik vgre, ha a szintaktikai ellenrzs nem jelzett hibt. A hnap
rtke 1 s 12 kzt, a nap 1 s 31 kzt vltozhat. Ha az rtkek valamelyike
hibs, ezt a program rja ki a kpernyre.
2. ltalnos feladatok 29
Heckl Istvn, PE www.tankonyvtar.hu
Az input fjl formtuma:
v. Hnap. Nap.
Plda bemenet:
2007. 12. 31.
Kimenet:
2007. 12. 31.
*******************************
I found 0 errors
Plda bemenet:
2007 1u2. 31
Kimenet:
2007 1u2. 31
Error: A "." have to follow the number, not "7"!
Error: the Month cannot contain u character!
Error: A "." have to follow the number, not "1"!
*******************************
I found 3 errors
Plda bemenet:
2007. 13. 0.
Kimenet:
2007. 13. 0.
Error: There are only 12 months!
Error: There are at most 31, at least 1 days in a month!
*******************************
I found 1 errors

2.55.2. rja t az elz programot gy, hogy csak szemantikai ellenrzs legyen, de
abbl szigorbb! Az v 1000 s 3000 kzti rtk lehet. A hnap 1 s 12 kzti
rtk lehet. A nap rtke 1 s 31 kztt lehet janurban, mrciusban, mjusban,
jliusban, augusztusban, oktberben s decemberben. A nap rtke 1 s 30 kzti
rtket vehet fel prilisban, jniusban, szeptemberben s novemberben. Ha az v
szkv, februrban a nap rtke 1 s 29 kzt lehet, ha nem, akkor 1 s 28
kztt. Szkv minden 4-gyel oszthat v, de a 100-zal oszthatak nem. A
400-zal oszthat vek mindig szkvek. Pldul 1992, 1996, 2000, 1600
szkv, de 1800, 1900 nem az. A program elsknt az vet s a hnapot
ellenrizze, majd ha ezek megfelelek, akkor a napot is! rja ki a kpernyre a
felfedezett hibkat!
2.56. Pascal hromszg
2.56.1. rjon programot, amely kirja a kpernyre a Pascal hromszg els 10 sort!
Kt szm kztt 4 szkz karakter legyen! Az r-edik sor i-edik tagjt szmolja a
kvetkezkplettel:
r! / ( i! * ( r - i )! )
Kimenet:
1
1 1
30 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
2.57. Lott
2.57.1. rjon lott-generl programot! A program generljon 1 s 90 kztt 5
klnbz pozitv egsz szmot! Egy fjl tippeket tartalmaz. Olvassa be a tippe-
ket a fjlbl, majd hasonltsa ssze ket a generlt szmokkal! rja ki a kp-
ernyre a generlt nyerszmokat, s azt, hogy hny embernek van 1-es, 2-es, 3-
as, 4-es, illetve 5-s tallata a lottn!
Az input fjl formtuma:
Els sor: a tippek szma
Minden tovbbi sor 5 tippet tartalmaz, szkz karakterekkel elvlasztva.
Plda bemenet:
6
5 64 23 80 42
4 34 44 62 72
75 43 3 64 80
53 52 21 56 10
1 37 87 9 53
75 10 64 69 78
Kimenet:
Generated numbers: 55, 64, 68, 75, 50
There is 1 1 hit
There are 2 2 hits
There is 0 3 hit
There is 0 4 hit
There is 0 5 hit
2.58. Hanoi tornyai
2.58.1. A Hanoi tornyai jtk 3 rudat tartalmaz (start, segd, cl). Az els rdon N db
korong van egyms fltt, amelyek klnbz mretek. A korongok fentrl
lefel nvekv sorrendben kvetkeznek, legnagyobb van legalul, a legkisebb
legfell, ahogyan az brn lthat. A feladat a kvetkez: a korongokat t kell
rakni a start rdrl a clra, a segdrd segtsgvel. Az traks szablya, hogy
nagyobb korongot kisebbre nem rakhatunk r. rjon programot ennek a feladat-
nak a szimullsra! A program argumentumknt megkapja N rtkt. Kezdet-
ben minden korong a start rdon van. Minden lpsben krdezze meg, melyik
rdrl melyikre tegyk t a legfels korongot! Ha ez nem ellenkezik a szab-
lyokkal, helyezzk t a korongot! Minden mozgats utn rja ki a kpernyre a
korongok helyzett, a pldban lthat mdon! Ha a felhasznl 0-t gpel, vagy
2. ltalnos feladatok 31
Heckl Istvn, PE www.tankonyvtar.hu
minden korong a cl rdon van, a program vget r. Hasznljon dinamikus tm-
bket s struktrkat a korongok helynek trolsra!

2.4. bra: Hanoi tornyai szemlltetse
Plda bemenet:
*************************************
Source: 3, 2, 1
Auxiliary: 0
Destination: 0
From: aux
To: src
Incorrect step!
*************************************
Source: 3, 2, 1
Auxiliary: 0
Destination: 0
From: src
To: aux
*************************************
Source: 3, 2
Auxiliary: 1
Destination: 0
From: src
To: dst
*************************************
Source: 3
Auxiliary: 1
Destination: 2
From: aux
To: dst
*************************************
Source: 3
Auxiliary: 0
Destination: 2, 1
From: 0
The disks are not on the destination!
*************************************
Source: 3
Auxiliary: 0
Destination: 2, 1
2.59. Trtek sszeadsa
2.59.1. Egy fjl tbb trtet tartalmaz. rjon programot, amely beolvassa a trteket, s
sszeadja ket! Minden sszeads utn szmolja ki az aktulis sszeg szmll-
jnak s nevezjnek legnagyobb kzs osztjt az Euklideszi algoritmus segt-
32 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
sgvel, s ha lehet, akkor egyszerstse a trtet, majd folytassa az sszeadst!
Minden mveletet rjon ki a kpernyre a pldban lthat mdon! Az Eukli-
deszi algoritmus megadja kt szm legnagyobb kzs osztjt.
procedure Euclidean(A, B)
M = B
while M is not zero {
B = M
M = A mod B // M az A / B oszts maradka
A = B
}
Az input fjl formtuma:
Els sor: a trtek szma
A tbbi sorban kt pozitv egsz tallhat, az els a szmll, a msodik a nevez rtke.
A kt rtk szkz karakterrel van elvlasztva.
Plda bemenet:
3
2 3
4 5
6 11
Kimenet:
2 4 22
------ + ------ = ------
3 5 15

22 6 332
------ + ------ = ------
15 11 165

332 4 1656 184
------ + ------ = ------ = ------
165 3 495 55
2.60. Nevezetes szmok
Szmelmlettel mr az kori Grgorszgban is sokat foglalkoztak, pldul sok nevezetes
tulajdonsg szmot prbltak meghatrozni.
2.60.1. rjon programot, amely megszmolja, hogy 1 s 10000 kztt mennyi tkletes
szm van! Tkletes szmnak tekintjk azokat a szmokat, amelyekre igaz,
hogy megegyeznek az osztik sszegvel. Az osztk kz az 1-et is hozz-
vesszk, de magt a szmot nem. Pldul tkletes szm a 6, mert 1 + 2 + 3 = 6.
2.60.2. rjon programot, amely megszmolja, hogy 1 s 100 kztt mennyi hinyos
szm tallhat! Hinyos szm az, amely nagyobb az osztinak sszegnl,
nmagt nem szmtjuk az oszti kz. Pldul a 21 hinyos szm, mert 1 + 3 +
7 < 21.
2.60.3. rjon programot, amely megszmolja, hogy 1 s 1000 kztt mennyi bvelked
szm tallhat! Bvelked szm az, amely kisebb az osztinak sszegnl,
2. ltalnos feladatok 33
Heckl Istvn, PE www.tankonyvtar.hu
nmagt szintn nem szmtjuk az oszti kz. Pldul a 12 bvelked szm,
mert 1 + 2 + 3 + 4 + 6 > 12.
2.60.4. Mdostsa az elz feladatot gy, hogy azon 1 s 1000 kztt tallhat
bvelked szmokat adja meg, amelyek 2-vel vagy 3-al oszthatak!

34 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3. Tmbk s mtrixok feladatai
3.1. Egy sztring cmei
3.1.1. Ksztsnk programot, amely bekr egy legfeljebb 6 karakter hossz sztringet s a
karakteres kpernyn megjelenti azt gy, hogy kirja az egyes karakterek rtkeit,
karakteresen s ASCII kddal 16-os szmrendszerben, valamint kirja az egyes karakter
vltozknak a neveit s ezeknek a cmeit. tlet mutatk kirshoz hasznlja a %p-t!

3.1. bra: Lehetsges kpernykp
3.1.2. Alaktsa t a program kirst gy, hogy a bekrt sz fgglegesen jelenjen meg s a
hozz tartoz kirsok az egyes karakterektl jobbra helyezkedjenek el!
3.2. Oszts s maradkkpzs
3.2.1. Troljon kt tmbben 5-5 egsz szmot, az osztkat s az osztandkat! Az rtkeket
inicializlssal adja t a tmbknek, legyen kztk negatvok is! Tippelje meg az
egszoszts s maradkkpzs eredmnyt! rja ki a helyes vlaszt s szmolja, a helyes
vlaszok szmt! tlet: ellenrizze, hogy a msodik tmbben ne legyen nulla!
3.2.2. Tovbbra is meg kell tippelni a megoldst, de az operandusokat generlja
vletlenszeren -10 s 10 kztt! Vletlenszeren dntse el azt is, hogy egsz vagy
lebegpontos osztst vgez! Utbbinl fggvnyt kell hasznlni a maradkkpzsre.
Lebegpontos osztsnl mindig rja ki a tizedes pontot az operandusoknl!
3.3. Sztring konvertls
3.3.1. Ksztsen programot, amely statikus karaktertmbben lv 4 szmot tkonvertl short
int, int, float s double tpusra! A szmok sszegt rja be az eredeti tmbbe!
3.3.2. A kezdeti sztringben 3 double tpus szm legyen, az elst eggyel, a msodikat
kettvel, a harmadikat hrommal nveljk meg! A megnvelt rtkeket egy j tmbbe
rjuk ki norml alakban, 8 tizedes pontossggal s eljellel!
3.4. Sztring bekrs
3.4.1. Krjen be egy-egy sztringet gets, getchar s scanf segtsgvel! rja ki a sztringeket
puts, putchar s printf segtsgvel!
3. Tmbk s mtrixok feladatai 35
Heckl Istvn, PE www.tankonyvtar.hu
3.4.2. Mi trtnik, ha a gets s a scanf rszeket felcserljk? Hogyan kezelhet a helyzet?
3.5. Gykk
3.5.1. rjon programot, amelyben egy 5 hossz statikus float tmb minden elembe a
hozztartoz index gykt rja be! Hasznljon for ciklust az egyes elemek elrshez s
az eredmny kirshoz! Az egyes rtkek vesszvel legyenek elvlasztva!
3.5.2. Oldja meg, hogy az utols szm utn ne jelenjen meg vessz a kirsnl s hogy a tmb
nagysgt szabadon lehessen meghatrozni!
3.6. Tmb reprezentlsa
3.6.1. A karakteres kpernyn reprezentljon egy 4 hossz egsz tmbt! Krje be a tmb
elemeit s rja ki az rtkeket '*' szimblumokbl ksztett ngyzetekbe! Adja meg az
egyes elemek indexeit s cmeit! rja ki a tmb mint mutat rtkt s annak a cmt!

3.2. bra: Lehetsges kpernykp
3.6.2. Oldja meg ugyanezt a feladatot dinamikus tmbre is! Hol lesz eltrs?
3.7. Magassg mrs
3.7.1. Feladat: rjon programot, amelyben egy 10*10-es statikus, inicializlt, float rtkeket
tartalmaz mtrix tengerszint feletti magassg adatokat reprezentl! Adja meg a
szrazfld s a tenger arnyt, ha a negatv magassg tengerfeneket reprezentl! Adja
meg a legmagasabb pontot s adja meg a legmagasabb pontot a tengerben feltteles
maximum keress segtsgvel! Azt az esetet is kezelni kell, amikor nincs tenger!
Szmolja ki a terlet tlagos magassgt!
3.7.2. Hatrozza meg a legnagyobb szintklnbsget a teljes terleten, csak a szrazfldn,
csak a tengerben!
3.8. Kockadobs
3.8.1. rjon programot, amely kockadobst szimull vletlen szmok generlsval! Krjen be
egy sorozat hosszt, x-t, s addig generljon vletlen szmokat, amg nem jelenik meg
egyms utn x darab hatos! Hny dobs utn kaptuk meg a kvnt eredmnyt? Szmolja
az egyes dobsok gyakorisgt!
36 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.8.2. Mdostsa gy az elz programot, hogy egy x rtkre 30-szor fusson le a program!
tlagosan hny dobs szksges x darab egymst kvet hatoshoz?
3.9. Cssztats
3.9.1. rjon fggvnyt, amely 3 cm szerint tadott float paramter rtkt (a, b s c)
elcssztatja a kvetkez mdon: ciklikus eltols: a b, b c, c a, nem ciklikus
eltols: a b, b c, 0 a! Egy negyedik paramter jelezze, hogy az eltols ciklikus-e!
3.9.2. 3 vltoz helyett egy 3 elem tmbn vgezze el az elcssztatst!
3.9.3. Egy plusz vltoz jelezze, hogy melyik irnyba trtnik a cssztats! A tmb mrete
legyen megadhat!
3.10. Mveletek tmbkn
3.10.1. rjon fggvnyeket a kvetkez feladatokra: hatrozza meg egy tmbben lv elemek
sszegt, tlagt, minimumt, hogy egy adott elem szerepel-e benne! Egy fjlban
legyen a main fggvny s egy msikban a tbbi fggvny!
3.10.2. Egsztse ki az elz programot a kvetkez feladatokat ellt fggvnyekkel!
Maximlis eleme indexnek a meghatrozsa, szrs kiszmtsa, kt tmb elemeinek a
felcserlse!
3.10.3. Egsztse ki az elz programot a kvetkez feladatokat ellt fggvnyekkel! Adott
elem els elfordulsnak meghatrozsa, utols elfordulsnak meghatrozsa, kt
tmb kztt az alapmveletek elvgzse az azonos index elemek kztt, skalris
szorzat meghatrozsa.
3.11. Sztring talakts
3.11.1. rjon programot, amely egy szveg minden negyedik karaktert kihagyja, ha az nem
white space! inicializlja gy a sztringet, hogy abban tbb sor legyen s ezek a sorok a
program kdban is sorokban legyenek (kln idzjel prok felhasznlsval)! A
nggyel val oszthatsgot kln fggvnnyel valstsa meg!
3.11.2. Mdostsa gy a programot, hogy a magnhangzkat hagyja ki, de csak akkor, ha nem
egy sz elejn vannak!
3.12. Szveg statisztika
3.12.1. Ksztsen magnhangz statisztikt egy bekrt sorrl! A magnhangz kis s nagy
bets alakjt nem klnbztetjk meg, csak az angol magnhangzkat tekintjk.
3.12.2. Ksztsen statisztikt egy szvegben lv szavak s mondatok szmrl!
3.13. Kdolt beszd
3.13.1. rja meg a tuvudsz ivigy beveszevelnivi programot! A kimenet csupa nagybet
legyen! rja meg azt a fggvnyt, amely eldnti, hogy egy bet magnhangz-e!
3. Tmbk s mtrixok feladatai 37
Heckl Istvn, PE www.tankonyvtar.hu
3.13.2. Bvtse gy a programot, hogy az j sztring egy megfelelen hossz dinamikus tmbbe
kerljn! Ksztse el a visszafele kdol fggvnyt!
3.14. Sztring kivons
3.14.1. rjon programot, amely egy sztringbl kivon egy msikat! Pldul: almafavirg - fa =
almavirg. Ha a msodik paramter nincs az elsben, akkor ne vltozzon az els
paramter rtke!
3.14.2. Mdostsa gy a programot, hogy a msodik sztring minden elfordulst kiveszi az
elsbl!
3.15. Kisbet - nagybet
3.15.1. rjon programot, amely bekrt mondatot formz adott vlaszts szerint! Menbl
vlaszthatak a kvetkez lehetsgek: UPPER CASE (mindent nagybetre), lower
case (mindent kisbetre), tOGGLE CASE (kis betket nagyra s nagyokat kicsire),
Sentense case (a sor els betje nagy csak), Title Case (minden szkezd bet nagy).
Mind a konvertlsok, mind a men fggvnnyel legyen megoldva!
3.15.2. Valstsa meg a Nice Title Case formzst! A szavak els betje nagy kivve az
albbi szavak esetn: and, of, the, a, an, from, for, in. A kivtelt nem kell figyelembe
venni a sor els karakternl s egy ketts pont utn. Pldul: The Life of an English
Man and the War
3.16. Tmbnvels
3.16.1. rjon programot, amely bekri egy tmb mrett, lefoglalja a helyet a tmb szmra s
feltlti elemekkel! Nvelje meg a tmb mrett dupljra gy, hogy ltrehoz egy j
tmbt, s belemsolja a rgi tmbt! Tltse fel a maradk helyet is j rtkekkel!
3.16.2. Alaktsa t gy az elz programot, hogy fggvnyben krje be tmb mretet s ott
hozza azt ltre!
3.17. Mtrixszorzs
3.17.1. rjon programot kt dinamikus mtrix sszeszorzsra! Fggvnyben foglaljon helyet a
mtrixoknak, amelyeket vletlen egszekkel tltsn fel! rjon fggvnyt a
mtrixszorozsra, ellenrizze, hogy a mtrix mrtek kompatibilisek-e, a fggvny
visszatrsi rtke legyen az j eredmny mtrix! rassa ki az eredetei s az eredmny
mtrixokat fggvnyben, majd szabadtsa fel azokat!
3.17.2. Ksztse el az jramretez fggvnyt, amely vagy levg a mtrixbl egy darabot,
s/vagy a mtrix jobb oldalhoz illetve aljhoz hozzfz egy j rszt! Az j rsz
egysgmtrix szeren tartalmazzon 0-kat s 1-ket, ha az j rsz nem ngyzet alak,
akkor az egyesek frszfog szeren helyezkedjenek el!
1 1 1
1 1
1 1
3.3. bra: Tglalap alak egysgmtrix
38 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.18. Virtulis memria
3.18.1. Krje be egy lebegpontos tmb mrett! Ha az 5 vagy kisebb, akkor hozzon ltre
dinamikus tmbt a memriban, ha nagyobb, akkor pedig binris fjlt a httrtron!
Ksztsen struktrt, amely tartalmaz egy FILE*, double* s mret adattagot! Ksztsen
fggvnyeket: trol inicializlsra s felszabadtsra, trol adott pozcijban
trtn olvassra s rsra. Menben krje be, hogy rni vagy olvasni akar, a f
fggvny szmra a trols mdja legyen transzparens!
3.19. Gpels
3.19.1. Ksztsen gpelst tant programot! Sztring tmbben troljon 20 klnfle szt! Krje
be, hogy hny szt akar gpelni, vletlenszeren vlasszon ki egyet, amit megjelent, s
aztn vrja azt bemenetknt! Hibs bevitel esetn krje be jbl a szt! A gyakorls
vgn rja ki az eltelt idt s a helyes s elrontott szavak szmt!
3.20. Nagy szmok sszeadsa
3.20.1. rjon programot kt nagyon nagy pozitv egsz szm sszeadsra! A szmok legfeljebb
100 jegyek. rja ki a kpernyre a kt szmot, majd az sszegket, a kvetkez
formtumban. A kt szmot fjlbl olvassa be, a szmok szkzzel vannak elvlasztva.
A szmokat statikus karaktertmbkben trolja!
Plda bemenet:
434234643643746 575434253245430
Kimenet:
434234643643746 + 575434253245430 = 1009668896889176
3.21. Medin
3.21.1. rjon programot, amely szmokat olvas be fjlbl, majd kiszmtja ezek tlagt s
medinjt! A program rja ki a kpernyre a szmokat, az tlagot, s a medint is! A
medin kiszmtshoz elszr sorba kell rendeznie a szmokat. Pratlan szm adat
esetn a medin ebben a sorban a kzps elem, pros szm adat esetn a kt kzps
elem tlaga.
Az input fjl formtuma:
Els sor: Az adatok szma.
Msodik sor: A szmok, egy-egy szkz karakterrel elvlasztva.
Plda bemenet:
30
4 2 5 3 4 2 5 1 3 5 1 5 5 5 4 4 3 4 4 2 5 5 1 5 5 3 2 5 2 5
Kimenet:
30 numbers:
4 2 5 3 4 2 5 1 3 5 1 5 5 5 4 4 3 4 4 2 5 5 1 5 5 3 2 5 2 5
The average is 3.63333
The median is: 4
3. Tmbk s mtrixok feladatai 39
Heckl Istvn, PE www.tankonyvtar.hu
3.22. sztndj
3.22.1. rjon programot, amely kiszmtja a hallgatk sztndjt a tanulmnyi tlaguk alapjn!
Fjl tartalmazza a hallgatk adatait: neptun kdjukat, s a trgyaik kreditrtkt, illetve
a szerzett rdemjegyeket. A program rja ki a kpernyre minden hallgat esetben a
neptun kdot, a felvett trgyak szmt, a szerzett rdemjegyek kredittel slyozott
tlagt, a felvett s a teljestett kreditek sszegt, s a hallgat szmra megtlt
sztndjat! Egy trgy teljestett, ha a hallgat tment az adott trgybl. Az tlagba a
felvett trgyak s nem a teljestettek tartoznak.
Az sztndjak sszege:
0 <= tlag < 2 0 HUF
2 <= tlag < 3 15 000 HUF
3 <= tlag < 4 20 000 HUF
4 <= tlag < 4.5 25 000 HUF
4.5 <= tlag <= 5 30 000 HUF
Az input fjl formtuma:
Els sor: A hallgatk szma.
A hallgatk adatait tartalmaz sor:
Sztring number1 // Sztring: a hallgat neptun kdja (6 karakter)
// number1: a felvett trgyak szma
Az egyes trgyakhoz tartoz sor:
number2 number3 // number2: a trgy kreditrtke, number3: a trgybl szerzett rdemjegy
Plda bemenet:
2
TGDS32 3
4 2
3 5
3 4
FBG4SW 3
4 5
2 3
4 1

A TGDS32 s FBG4SW neptun kd hallgat adatait ltjuk. TGDS32 3 trgyat vett fel, az els
trgya 4 kredit rtk, az rdemjegye belle 2.
Kimenet:
Neptun: TGDS32 3 subjects
Neptun: FBG4SW 3 subjects
TGDS32:
Credits: 10/10
Average: 3.5
Bursary: 20000 HUF
FBG4SW:
Credits: 10/6
Average: 3
Bursary: 20000 HUF
40 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.23. Szavak keresse
3.23.1. rjon programot, amely beolvassa a dune.txt nev fjlt s keresi benne az Atreides
szt! A program rja ki a kpernyre az sszes tallatot az eltte lv szval egytt! rja
ki a tallatok szmt is! Ha egy rsjel szerepel az Atreides sz utn, pl. Atreides.,
Atreides,, az j tallatnak minsl, azonban amikor az Atreides sz egy rszsztringje
egy sznak, azt nem tekintjk j tallatnak, pl. Atreides-Harkonnen, Atreides's.
Az input fjl formtuma:
A szavak szkz karakterekkel vannak elvlasztva.
Plda bemenet:
Leto Atreides is the head of the Atreides house. Leto Atreides's son is
Paul.
Kimenet:
Leto Atreides
the Atreides
2 hits
3.24. Egyszer sztringfordt
3.24.1. rjon programot, amely beolvas egy fjlbl utastsokat s vgrehajtja a benne
foglaltakat! Az utastsok hrom integer tpus vltozt hasznlhatnak: A, B, C. A
script elejn a vltozk rtke 0. A lehetsges utastsok a kvetkezk:
GET Op: Op lehet egy vltoz (A, B, or C), ez a parancs beolvas egy tzes szmrendszerbeli
szmot a billentyzetrl, s az Op-ban trolja.
WRITE Op: Op rtkt a kpernyre rja.
ADD Op1 Op2: Hozzadja Op2-t Op1-hez, azaz Op1 = Op1 + Op2.
SUB Op1 Op2: Kivonja Op2-t Op1-bl, azaz Op1 = Op1 - Op2.
MUL Op1 Op2: Megszorozza Op1-et Op2-vel, azaz Op1 = Op1 * Op2.
DIV Op1 Op2: Elosztja Op1-et Op2-vel, azaz Op1 = Op1 / Op2.
STOP: Ez a parancs a script vgt jelzi.

Minden sorban csak egy parancs szerepel. Ha a sor # karakterrel kezddik, azt a sort
megjegyzsnek tekintjk. Ezeknek a soroknak a vgt is egy # karakter jelzi. Az els # utn egy
szkz karakter kvetkezik. A program rja ki ezeket a sorokat a kpernyre, a # karakterek
kivtelvel! Pldul ha a sor a kvetkez # This is a comment! #, a program a kvetkezt rja ki:
This is a comment!
Plda bemenet:
# Type A: #
GET A
# Type B: #
GET B
ADD A B
# The sum: #
WRITE A
STOP
3. Tmbk s mtrixok feladatai 41
Heckl Istvn, PE www.tankonyvtar.hu
Kimenet:
Type A: 1
Type B: 2
The sum: 3
3.25. Riemann integrl
3.25.1. rjon programot, amely ngy fggvny Riemann-integrljt szmtja ki 0 s 1 kztt!
Elsknt az [a, b] intervallumot felosztjuk N db (1000000) rszre, azaz egy kis
intervallum hossza: h = (b - a)/N. N tglalapot kpznk gy, hogy egyik tglalap se
lgjon a fggvny fl. Az i-dik tglalap alapja teht h magassga pedig f(h*i) s f(h*(i
+ 1)) kzl a kisebbik. Az integrl a tglalapok sszege. A szmoland fggvnyek:
f1(x) =
f2(x) = x
2

f3(x) = sin(x)
f4(x) = tan(x)

bra: Riemann integrl szemlltetse
Plda bemenet:
The Riemann integral of f1(x) over x from 0 to 1: 3.14159
The Riemann integral of f2(x) over x from 0 to 1: 0.333332
The Riemann integral of sin(x) over x from 0 to 1: 0.459696
The Riemann integral of tan(x) over x from 0 to 1: 0.615624
3.26. Polinomok sszeadsa
3.26.1. rjon programot, amely polinomokat ad ssze! Olvasson be fjlbl kt polinomot! rja
ki a kpernyre a kt polinomot, illetve ezek sszegt! A polinomok trolsra
hasznljon dinamikus tmbket s struktrkat.
Az input fjl formtuma:
Els sor: Number1 - az els polinom foka
Msodik sor: Number1 + 1 egsz szm, az els polinom egytthati (az utols szm a konstans).
Harmadik sor: Number2 - a msodik polinom foka
Negyedik sor: Number2 + 1 egsz szm, a msodik polinom (az utols szm a konstans).
A szmok egy-egy szkz karakterrel vannak elvlasztva
Plda bemenet:
5
-3 5 -4 0 4 2
42 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
4
5 4 5 -1 0
Kimenet:
- 3x^5 + 5x^4 - 4x^3 + 4x + 2 +
5x^4 + 4x^3 + 5x^2 - x =
- 3x^5 + 10x^4 + 5x^2 + 3x + 2
3.27. Caesar dekdol
3.27.1. A Czr-kdols a kvetkezkppen mkdik: Minden karaktert egy elre meghat-
rozott N pozcival eltolunk. Pldul, ha N = 1, az APPLE sz BQQMD lesz, ugyanis
A-bl B lett, P-bl Q, stb. Ha N = 1, Z-bl A lesz. Plda N = 3-ra:
eredeti szveg: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
kdolt szveg: WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ
Az ellensgtl egy kdolt zenetet kaptunk. Nem ismerjk N rtkt, de a kmnk azt lltja, hogy
az eredeti zenet szavai kzt szerepel a THE sz. rjon programot, amely beolvassa a kdolt
zenetet a codedmessage.txt fjlbl, s megfejti, mi volt az eredeti zenet! N rtke 1 s 26 kzt
van, a programnak teht meg kell vizsglnia minden N-t, amg az zenet nem tartalmazza a THE
szt. Az zenet trolsra hasznljon dinamikus tmbt!

bra: Caesar kdols szemlltetse
Az input fjl formtuma:
Els sor: Az zenet szavainak szma.
Msodik sor: Az zenet szavai, egy-egy szkz karakterrel elvlasztva.
Plda bemenet:
9
WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ
Kimenet:
The coded message: WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ
The original message: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

3.27.2. Legyen a tartalmazott sz, a mostani THE is bemenet! Ha tbb lehetsges
visszakdols van, akkor jelentse meg az sszest!
3.28. CD katalgus
3.28.1. Rendelkezik egy CD katalgussal, amit fjlban trol. rjon programot, amely kpes arra,
hogyha begpeli egy szoftver nevt, akkor megmondja, melyik CD-n van a szoftver! A
szoftverek nevei maximum 15 karakter hosszak, s minden CD-nek van egy neve,
3. Tmbk s mtrixok feladatai 43
Heckl Istvn, PE www.tankonyvtar.hu
amely szintn maximum 15 karakter hossz. Hasznljon struktrkat, illetve dinamikus
tmbket a fjlbl beolvasott adatok trolsra!
Az input fjl formtuma:
Els sor: A CD-k szma.
A tovbbi sorok:
String: A CD neve
Egsz szm: A CD-n lv szoftverek szma
Ezutn a CD-n lv szoftverek neve kvetkezik.
Plda bemenet:
2
2007/11
2
BurningStudio
RadioRama
2005/4
3
Doc2PDF
Apollo
Stellarium

A pldban Jamesnek 2 CD-je van, az els neve 2007/11, ezen a CD-n kt szoftver van:
BurningStudio s RadioRama. A msik CD 3 szoftvert tartalmaz.
Kimenet:
Software name: Apollo
The Apollo is here: 2005/4

3.28.2. rja t gy az elz programot, hogy lehessen a keressnl egy ? vagy egy * karaktert
hasznlni! A ? egy tetszleges karakter helyett llhat, a * pedig a sztring vgn lehet s
azt jelezi, hogy mg valamennyi karakter htra van. Ha egy minta tbb program nevre
is illeszkedik, akkor jelentse meg mindet!
3.29. Leltr
3.29.1. Egy cg termkek vsrlsval s eladsval foglalkozik. Az v elejn 10.000 Ft-ja van.
Egy fjlban trolja az informcikat a termkekrl, az eladsokrl s a beszerzsekrl.
rjon programot, amely a fjlbl beolvassa az adatokat, s megmondja az egyes
termkek mennyisgt, illetve a cg egyenlegt az eladsok s beszerzsek utn!
Hasznljon dinamikus tmbket s struktrkat az adatok trolsra!
Az input fjl formtuma:
Els sor: Number1 - a termkek szma
A kvetkez Number1 db sor:
String Number2 Number3 Number4
String: az i-edik termk neve
Number2: az i-edik termk mennyisge
Number3: az i-edik termk beszerzsi ra
Number4: az i-edik termk eladsi ra
Number5: a termkekkel kapcsolatos ads-vtelek szma
Az ezutn kvetkez Number5 db sor:
Number6 Number7
44 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Number6: Az aktulis termk indexe (nem a neve, hanem a sorszma)
Number7: Ha ez a szm pozitv, a cg beszerzett a Number6-os termkbl Number7 db-ot,
beszerzsi ron; ha negatv, akkor a cg a Number6-os termkbl eladott Number7 abszolt
rtknek megfelel szm darabot, eladsi ron.
Plda bemenet:
2
hammer 100 500 800
screwdriver 50 300 400
2
1 10
2 -5

A pldafjl esetben ktfle termknk van: 100 db hammer s 50 db screwdriver. A cg 500 Ft-rt
tud hammer-t beszerezni, s 800 Ft-rt tudja eladni. 2 fle termkmozgs trtnt, elszr vsroltak
500 Ft/db ron 10 db hammer-t, majd 400 Ft/db ron eladtak 5 db screwdriver-t.
Kimenet:
Inventory:
****************************************
hammer:
Count: 100
Purchase price: 500
Shop price: 800
screwdriver:
Count: 50
Purchase price: 300
Shop price: 400
Inventory:
****************************************
hammer:
Count: 110
Purchase price: 500
Shop price: 800
screwdriver:
Count: 45
Purchase price: 300
Shop price: 400
We have got 7000 HUF
3.30. Knyvtri rendszer
3.30.1. A knyvtrakban a knyvek az Egyetemes Tizedes Osztlyozs (ETO, angolul UDC)
szerint vannak osztlyozva. Minden knyvnek van egy ETO szma, amit a knyv
tmja hatroz meg. Az ETO szm els szmjegye a f tmt hatrozza meg:
0. ltalnos mvek, bibliogrfia, knyvtrgy.
1. Filozfia, pszicholgia, logika, etika.
2. Valls, egyhzak, teolgia.
3. Trsadalomtudomnyok, kzigazgats, jog, oktats.
4. Nem hasznlt
5. Matematika, termszettudomnyok, fizika, kmia.
6. Alkalmazott tudomnyok, mszaki tudomnyok, orvostudomnyok.
3. Tmbk s mtrixok feladatai 45
Heckl Istvn, PE www.tankonyvtar.hu
7. Mvszetek, jtk, sport, szrakozs.
8. Nyelvszet, irodalom
9. Rgszet, fldrajz, letrajz, trtnelem

Pldul egy 543-as ETO szm knyvrl tudjuk, hogy matematikval, vagy termszet-
tudomnyokkal foglalkozik. A tbbi szmjegy a program szempontjbl nem fontos. A lib1.txt
fjlban knyvek adatai szerepelnek. A fjl tartalmazza a szerz nevt, a knyv cmt, a kiadsi vet
s a knyv ETO szmt. rjon programot, amely beolvassa ezt a fjlt, listzza az egyes knyveket,
vgl sszestst ad, hogy hny knyv tallhat a knyvtrban egy-egy a tmban! Hasznljon
dinamikus tmbket s struktrkat az adatok trolsra!
Az input fjl formtuma:
Els sor: A knyvek szma.
A tbbi sor formtuma: Szerz Rvid_Cm Kiadsi v ETO (szkz karakterekkel elvlasztva).
A szerz neve s a knyv cme maximum 20 karakterbl ll, mindkett egy-egy sz csak. Az ETO
szm 3 karakterbl ll.
Plda bemenet:
3
Asimov Foundation 1980 820
Herbert Dune 1990 820
Dancs Terror 2001 512
Kimenet:
Author: Asimov
Title: Foundation
Year of edition: 1980
UDC: 820 Language, Linguistics, Literature

Author: Herbert
Title: Dune
Year of edition: 1990
UDC: 820 Language, Linguistics, Literature

Author: Dancs
Title: Terror
Year of edition: 2001
UDC: 512 Matematika and natural sciences
**************************************
Generalities: 0 books
Philosophy, Psychology: 0 books
Religion, Theology: 0 books
Social sciences: 0 books
vacant: 0 books
Matematika and natural sciences: 1 books
Applied sciences, Medicine, Technology: 0 books
Arts, Recreation, Entertainment, Sport: 0 books
Language, Linguistics, Literature: 2 books
Geography, Biography, History: 0 books
3.31. Kiklcsnztt knyvek
3.31.1. A knyvtrak nyilvntartst vezetnek a kiklcsnztt knyvekrl. Ez tartalmazza a
knyvek szerzjt, cmt, illetve a klcsnzs lejratnak idejt. Ttelezzk fel, hogy az
aktulis dtum 2008. december 15. rjon programot, amely beolvassa a kiklcsnztt
46 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
knyvek listjt egy fjlbl, s kilistzza azoknak a knyveknek az adatait, amelyek
klcsnzsi ideje mr lejrt! Hasznljon dinamikus tmbket s struktrkat az adatok
trolsra!
Az input fjl formtuma:
Els sor: A knyvek szma.
A tbbi sor: Szerz Rvid_cm v Hnap Nap
A szerz neve s a knyv cme is egy-egy sz csak. Az v, hnap, nap a lejrat idejt jellik.
Plda bemenet:
3
Asimov Foundation 2009 1 20
Herbert Dune 2008 12 1
Dancs Terror 2008 11 30
Kimenet:
Title: Herbert
Author: Dune
Expiraton: 2008 12 1

Title: Dancs
Author: Terror
Expiraton: 2008 11 30
3.32. Sztr
3.32.1. rjon angol-magyar sztr programot! Fjl tartalmazza az angol-magyar szprokat! A
program olvasson be egy szt a billentyzetrl! A sz a kt nyelv brmelyikn lehet.
Ezutn olvassa be a szprokat a fjlbl, s keresse meg a megadott szhoz tartoz
szprt! Az is tallatnak szmt, ha a begpelt sz, az eltagja az egyik sztri
bejegyzsnek. rja ki a kpernyre a tallatokat!
Az input fjl formtuma:
Els sor: A szprok szma
A tbbi sor: Angol_sz Magyar_sz (szkz karakterrel elvlasztva)
Egy-egy sz maximlis hossza 20 karakter.
Plda bemenet:
5
SUN NAP
DOG KUTYA
BICYCLE BICIKLI
VILLAGE FALU
SUNSHINE NAPSUTES
Kimenet:
Type the word: NAP
Hun->Eng: NAP SUN

1 hits
3. Tmbk s mtrixok feladatai 47
Heckl Istvn, PE www.tankonyvtar.hu
Kimenet:
Type the word: SUN
Eng->Hun: SUN NAP
Eng->Hun: SUNSHINE NAPSUTES

2 hits
3.33. Sudoku ellenrz
3.33.1. rjon programot, amely leellenriz egy kitlttt Sudoku tblt! A tbla rtkeit olvassa
be fjlbl! Egy tbla akkor van helyesen kitltve, ha minden sorban, minden oszlopban
s minden kis 3x3-as kis ngyzetben az 1-9 kzti szmjegyek mindegyike egyszer
szerepel. Az brn egy helyesen kitlttt tbla szerepel.
9 5 8 2 7 4 6 3 1
1 4 7 5 3 6 9 2 8
2 6 3 9 8 1 4 7 5
8 3 1 4 6 9 2 5 7
4 2 5 3 1 7 8 9 6
7 9 6 8 5 2 1 4 3
3 1 4 7 2 8 5 6 9
5 8 9 6 4 3 7 1 2
6 7 2 1 9 5 3 8 4
bra: Sudoku tbla
Az input fjl formtuma:
Az input fjl 9 sort s 9 oszlopot tartalmaz. A szmjegyek egy-egy szkz karakterrel vannak
elvlasztva.
Plda bemenet:
7 4 6 8 3 1 5 9 2
9 2 3 5 7 4 8 6 1
8 1 5 2 9 6 4 7 3
1 3 4 7 5 2 6 8 9
6 9 7 3 1 8 2 5 4
5 8 2 4 6 9 1 3 7
4 7 9 6 2 8 3 1 8
3 6 8 1 4 7 9 2 5
2 5 1 9 8 3 7 4 6
Kimenet:
This is a wrong table!
3.34. Amba jtk
3.34.1. rjon egy egyszer amba jtkot, 3x3-as plyra! Kt jtkos jtszhat a programmal,
akik a sajt jelket helyezhetik a mezkbe felvltva (X vagy O). Az a jtkos nyeri a
48 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
jtszmt, akinek 3 jele lesz egy sorban, oszlopban vagy tlban. Ha nincs tbb res
cella, vagy a jtkosok valamelyike nyer, a jtk vget r. A programnak minden lps
utn ki kell rajzolnia a jtktbla aktulis llst karakteresen! Felttelezzk, hogy
mindkt jtkos megfelel pozcit ad meg minden lpsben.
Plda bemenet:
A B C
-------
1| | | |
-------
2| | | |
-------
3| | | |
-------
First player
Target: A1
A B C
-------
1|X| | |
-------
2| | | |
-------
3| | | |
-------
Second player
Target: B1
A B C
-------
1|X|O| |
-------
2| | | |
-------
3| | | |
-------


First player
Target: A2
A B C
-------
1|X|O| |
-------
2|X| | |
-------
3| | | |
-------
Second player
Target: A3
A B C
-------
1|X|O| |
-------
2|X| | |
-------
3|O| | |
-------
First player
Target: B2
A B C
-------
1|X|O| |
-------
2|X|X| |
-------
3|O| | |
-------
Second player
Target: C1
A B C
-------
1|X|O|O|
-------
2|X|X| |
-------
3|O| | |
-------
First player
Target: C3
A B C
-------
1|X|O|O|
-------
2|X|X| |
-------
3|O| |X|
-------
First player won!
3.35. Trkp
3.35.1. Egy fjl egy magassgi trkpet tartalmaz. A magassgok pozitv egsz szmok. rjon
programot, amely beolvassa ezt a trkpet egy mtrixba, kirja a kpernyre s
kiszmtja az adott terleten az alfld, dombsg, hegysg s magashegysg arnyt! A
mtrix legyen dinamikus! A magassgi intervallumok a kvetkezk:
0 <= magassg < 250 alfld
250 <= magassg < 500 dombsg
500 <= magassg < 1500 hegysg
1500 <= magassg magashegysg
Az input fjl formtuma:
Els sor: number1 number2
A number1 a sorok, number2 az oszlopok szmt adja meg.
Ezutn number1 db sor kvetkezik, minden sorban number2 db, szkz karakterrel elvlasztott
rtk tallhat.
3. Tmbk s mtrixok feladatai 49
Heckl Istvn, PE www.tankonyvtar.hu
Plda bemenet:
5 5
200 210 220 218 230
0 1600 322 31 1000
332 320 43 1 545
2000 32 252 0 321
1320 2123 324 21 43
Kimenet:
200 210 220 218 230
0 1600 322 31 1000
332 320 43 1 545
2000 32 252 0 321
1320 2123 324 21 43

Lowland: 52 %
Hill: 24 %
Mountain: 12 %
High mountain: 12 %
3.36. Inverz mtrix
3.36.1. rjon programot, amely kiszmtja egy 3x3-as mtrix inverzt! A program rja ki a
kpernyre a mtrix adjungltjt, determinnst s az inverz mtrixot. Az inverz
mtrixot a kvetkezkppen szmthatjuk ki: A
-1
= adj(A) / det(A), ahol adj(A) az A
mtrix adjungltja, s det(A) az A mtrix determinnsa. Ha det(A) = 0, akkor A nem
invertlhat.
A = _
A
11
A
12
A
13
A
21
A
22
A
23
A
31
A
32
A
33
_
bra: Mtrix elemeinek az indexelse

Determinns:
A 2x2-es mtrix determinnsa a kvetkez: a11*a22 - a21*a12
A 3x3-as mtrix determinnsa: a11 * a22 * a33 + a12 * a23 * a31 + a13 * a21 * a32 - a13 * a22 *
a31 - a12 * a21 * a33 - a11 * a23 * a32
Adjunglt:
adj(A) =

+_
A
22
A
23
A
32
A
33
_ _
A
12
A
13
A
32
A
33
_ +_
A
12
A
13
A
22
A
23
_
_
A
21
A
23
A
31
A
33
_ +_
A
11
A
13
A
31
A
33
_ _
A
11
A
13
A
21
A
23
_
+_
A
21
A
22
A
31
A
32
_ _
A
11
A
12
A
31
A
32
_ +_
A
11
A
12
A
21
A
22
_


ahol
_
A
]
A
kI
A
mn
A
op
_ = det _
A
]
A
kI
A
mn
A
op
];
50 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Plda bemenet:
Original matrix:

1 2 3
2 4 5
3 5 6

Adjugate matrix:

-1 3 -2
3 -3 1
-2 1 0

Determinant of the matrix: -1
Inverse matrix:

1 -3 2
-3 3 -1
2 -1 -0
3.37. Mtrixmveletek
3.37.1. rjon programot mtrixsszeads s skalrral val szorzs megvalstsra! A program
olvassa be fjlbl kt mtrixot! Adja ssze a kt mtrixot, s az eredmnyt szorozza
meg 2-vel! A mtrixokat dinamikusan hozza ltre! Ha A, B s C azonos mret
mtrixok, akkor C
ij
= A
ij
+ B
ij
, ahol C az A s B mtrixok sszege. Egy mtrix d
skalrral val szorzsakor a mtrix minden elemt d-vel szorozzuk.
Az input fjl formtuma:
Els sor: Kt szm, az els a sorok, a msodik az oszlopok szma.
A tbbi sorban a kt mtrix tallhat, a pldban lthat mdon. Minden sorban egy-egy mtrix-sor
van, a szmok szkz karakterekkel vannak elvlasztva. A mtrixok elemei egsz szmok.
Plda bemenet:
2 3
4 3 4
3 1 5

2 4 1
1 7 3
Kimenet:
A :
4 3 4
3 1 5

B :
2 4 1
1 7 3

************************
(A + B) * 2 =
12 14 10
8 16 16
3. Tmbk s mtrixok feladatai 51
Heckl Istvn, PE www.tankonyvtar.hu
3.38. Morze kd
3.38.1. rjon programot, ami egy zenetet Morze kdd alakt! Az zenet begpelse utn a
program foglaljon le memrit a kdolt zenet szmra, kdolja az zenetet s jelentse
meg azt! Hasznlja az albbi sztring tmbt az egye karakterek lekpezsre! A szkz
karakter kdja 5 pont.
char* morsecodes[26] = { ".=", "=...", "=.=.", // A, B, C
"=..", ".", "..=.", // D, E, F
"==.", "....", "..", // G, H, I
".===", "=.=", ".=..", // J, K, L
"==", "=.", "===", // M, N, O
".==.", "==.=", ".=.", // P, Q, R
"...", "=", "..=", // S, T, U
"...=", ".==", "=..=", // V, W, X
"=.==", "==.."}; // Y, Z
Plda bemenet:
Az zenet: SOS I AM WRITING A TEST
zenet: "SOS I AM WRITING A TEST"
A kdolt zenet:
"...===................===......==.=...=..=.==.......=.....=....="
3.39. Mtrix szorzsa vektorral
3.39.1. rjon programot, amely megszoroz egy mtrixot egy vektorral! A mtrixot s a vektort
fjlbl olvassa be s trolja ket dinamikus adatszerkezetekkel! rja ki a kpernyre az
eredeti mtrixot s vektort, majd a szorzatvektort! A szorzatvektor annyi rtket
tartalmaz, amennyi a mtrix sorainak szma. Ha P a szorzatvektor, A a mtrix, s
V az eredeti vektor, akkor
P
i
= Sum(j=1c, A
ij
*V
j
), ahol A
ij
a mtrix i-edik sornak j-edik oszlopban van, c a
mtrix oszlopainak szma.
Az input fjl formtuma:
Els sor: num1 num2
num1: a mtrix sorainak szma
num2: a mtrix oszlopainak szma, amely egyben az eredeti vektor elemeinek szma is
A kvetkez num1 db sor a mtrix sorait tartalmazza, mindegyik sorban num2 db rtk tallhat,
szkz karakterrel elvlasztva.
A mtrix utn num2 db szm kvetkezik, az eredeti vektor elemei.
Plda bemenet:
2 3
4 1 3
7 2 2
6
2
3
Kimenet:
Matrix :
4 1 3
7 2 2
Vector :
6
52 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2
3
************************
Matrix * Vector =
35
52
3.40. Sztring tokenizl
3.40.1. rjon sztring tokenizl programot! A felhasznl egy sztringet gpel be, amely tbb
szbl llhat, a szavakat egy vagy tbb szkz karakter vlasztja el. Ezutn a program
szmolja meg a sztringben lv szavakat, foglaljon le dinamikus tmbket a szavak
szmra, s msolja be az egyes szavakat a lefoglalt karaktertmbkbe! rja ki a
program a kpernyre az eredeti sztringet, s az egyes szavakat!
Plda bemenet:
This is a simple example.
The typed text: "This is a simple example."
1.: "This"
2.: "is"
3.: "a"
4.: "simple"
5.: "example."
3.41. Szavak kicserlse
3.41.1. Egy fjlban egy legfeljebb 1000 karakter hossz sztring tallhat. rjon programot,
amely beolvassa ezt a fjlt, majd bekr a felhasznltl kt szt! A msodik sz nem
lehet hosszabb az elsnl. A program keresse meg az els sz minden elfordulst a
szvegben, s cserlje ki a msodik szra. rja ki a kpernyre az j szveget, s a
tallatok szmt!
Plda:
The original text: "This is a very simple text that can help for you to
understand the task. "

Type a word: simple
Type the new word: easy
1 hits

The new text: "This is a very easy text that can help for you to
understand the task. "
3.42. Ellenrz sszeg
3.42.1. rjon programot, amely kpes ellenrz sszeg generlsra egy zenethez, s ezen
sszeg alapjn ellenrizni tudja a bejv zeneteket! Az ellenrz sszeg kiszmtsa a
kvetkezkppen trtnik: Adjuk ssze az zenet minden bjtjt, ha az sszeg nagyobb,
mint 255, akkor az sszegnek csak a legkisebb bjtjt tekintjk. Az gy kapott bjt
kettes komplemense (255 - sum + 1) lesz az ellenrz sszeg. Pldul az ABCD
zenet bjtjai: 0x41, 0x42, 0x43 and 0x44, gy az sszeg = 0x41 + 0x42 + 0x43 + 0x44
= 0x10A. Ebbl legkisebb bjt: 0xA, a kettes komplemens pedig: 0xFF - 0xA + 0x1 =
0xF6. Az ellenrzs menete: Az zenettel egytt az ellenrz sszeg is megrkezik egy
3. Tmbk s mtrixok feladatai 53
Heckl Istvn, PE www.tankonyvtar.hu
fjlban. A programnak ssze kell adnia a berkezett zenet minden bjtjt s az
ellenrz sszeget. Ha az eredmny utols bjtja 0, akkor a berkezett zenet
valsznleg nem srlt. Egy fjl tbb zenetet tartalmaz, az ellenrz sszegkkel
egytt. A program olvassa be ezeket, s ellenrizze ket! rja ki a kpernyre az
zeneteket, az ellenrz sszegeket, s azt, hogy az zenetek hibsak vagy helyesek!
Vgl szmolja ki a This is a simple checksum example. zenet ellenrz sszegt!
Az input fjl formtuma:
Els sor: Az zenetek szma
A tbbi sor felvltva tartalmaz zeneteket s ellenrz sszegeket. Az zenetek soraiban tbb sz
is szerepelhet. Az zenet utn kvetkez sor az zenet ellenrz sszegt tartalmazza
hexadecimlis formban.
Plda bemenet:
2
This is the first row of the message.
C2
This is the second row ov the message.
6E
Kimenet:
"This is the first row of the message." C2 ===> Correct!
"This is the second row ov the message." 6E ===> Faulty!

Sum of "This is a simple checksum example.": C6C
The checksum: 94
3.43. Statisztika
3.43.1. Egy 5000 fs telepls lakosainak adatait kell feldolgoznunk. Van egy fjlunk, amely a
lakosok letkort tartalmazza. rjon programot, amely kirja a kpernyre, hogy mennyi
kiskor, felntt, nyugdjas l a telelsen! Kiskornak szmt az, aki mg nem tlttte
be a 18. letvt, egybknt a felnttek kz soroljuk. A nyugdjkorhatr 62 v.
3.43.2. Bvtse ki az elz programot gy, hogy a program kirja, hogy hnyan szlettek a
msodik vilghbor alatt (1939-1945). Az aktulis v 2010.
3.43.3. Bvtse ki az elz programot gy, hogy a program kirja azt is, hogy hnyan szlettek
szkvben! Szkvnek szmtanak azok az vek, ahol az vszm oszthat 4-el, de a
100-asra vgzdek kzl csak azok, amelyek oszthatak 400-al. Ez alapjn szkv
volt 1992, 1996, de 1900 nem, viszont 2000 igen.
3.44. Kerts
3.44.1. Egy 400 mter kerlet telket szeretnnk krlvenni drtkertssel. Tbb kteg
drtkertsnk van, amelyek hosszt egyenknt ismerjk. rjon programot, amely 0
vgjelig beolvassa az egyes ktegek hosszait, majd a vgn kirja, hogy sszesen hny
mternyi kertsnk van s, ha kell-e mg kertst vennnk, akkor sszesen mennyit!
54 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.45. Jegyek tlaga
Aladr v vgn szeretn kiszmolni, hogy mely tantrgybl hnyasra ll. Minden trgybl
sok jegyet szerzett, ezrt gy vli, fraszt munka lenne kzzel tlagokat szmolni, ezrt
szmtgpes segtsghez folyamodik.
3.45.1. rjon programot Aladrnak, amely beolvas 10 jegyet, majd kiszmolja azok szmtani
tlagt!
3.45.2. Bvtse ki az elz programot gy, hogy 0 vgjelig olvassa be a jegyeket s gy vgzi
el a szmolst!
3.45.3. Fejlessze tovbb a programot gy, hogy a jegyek szrst is meghatrozza! Hatrozza
meg az egyes jegyek tlagtl val eltrsit, utna ezen eltrsek ngyezeteinek az
tlagt, majd az gy kapott eredmny gykt!
3.46. Nyltenyszts
3.46.1. Mr. Fibonacci elhatrozta, hogy belevg a nyltenysztsbe. Az els hnapban vesz
egy jszltt nylprt. Minden nyl 2 hnap utn vlik termkenny. Minden hnapban
minden termkeny nylpr egy j nylprt szl. A nyulakat etetni kell, minden nyl egy
zsk nyltpot fogyaszt el minden hnapban s egy nylpr se pusztul el. rjon
programot, amely meghatrozza, hogy hny zsk nyltpot kell vsrolni egy vre, ha
az els hnapban 1 nylpr van!
3.46.2. Bvtse ki az elz programot gy, hogy 3 vre elre szmoljon, figyelembe vve, hogy
Mr. Fibonacci minden v elejn eladja a termkeny nyulak 90 %-t, s a termketlenek
95 %-t! Amennyiben az eladand nyulak mennyisge nem egsz szm, gy ezt az
rtket mindig lefele kerektjk. Pldul 101 termkeny nyl esetn 90-et adunk el.
3.47. Jegyek
3.47.1. Egy 30 fs osztlyban minden tanulrl tudjuk, hogy informatikbl mennyi a
jegyeinek az tlaga. rjon programot, amely billentyzetrl beolvassa a 30 tlagot, majd
kirja a kpernyre, hogy volt-e buks idn! Az bukik meg, akinek az tlaga kevesebb,
mint 1.5.
3.47.2. Mdostsa az elz programot gy, hogy addig olvassa be az tlagokat, amg bukott
embert nem tall! Amennyiben 0-t olvasunk be, az azt jelenti, hogy vge a
beolvassnak, vagyis ez nem egy tlag. A program ez esetben is rja ki, hogy bukik-e
valaki!
3.48. Marsjr
A Mars Explorer 3000-es marsjr robot utazsa sorn 100 mterenknt feljegyzi, hogy a
bolygn val leszllhelyhez viszonytva milyen magasan / mlyen jr, gy egy domborzati
keresztmetszetet tovbbt a fldi irnyt kzpontba. Szeretnnk rszletesen megvizsglni a bejrt
terepet. A vizsglatra szmtgpet hasznlunk. A domborzati magassgokat egy tmbben troljuk.
3.48.1. rjon programot, amely a tmbben trolt domborzati adatokbl meghatrozza, hogy
mekkora volt a legmagasabb, illetve legalacsonyabb magassg, ahol a marsjr jrt,
valamint hogy hol voltak ezek a pontok!
3. Tmbk s mtrixok feladatai 55
Heckl Istvn, PE www.tankonyvtar.hu
3.48.2. Kzeledik a marsbeli tl, ezrt a marsjr fldi vezeti attl flnek, hogy azeltt lell,
mieltt elklden a legjabb sszegyjttt mrseket. Ezrt belltjk, hogy minden
egyes mrs utn kldje el a Fldre az aktulis magassgt. rjon programot, amibe a
kezel szemly begpeli az aktulis kapott magassg rtket s minden j adat utn
kiszmolja, hogy eddig mekkora volt a legmagasabb s legalacsonyabb pont s hol
voltak azok!
3.48.3. Bvtse ki az elz programot gy, hogy azt is nyilvn tartsa a legmeredekebb lejt s
emelked meredeksgt, valamint pozcijt! Megjegyzs: kt mrsi adat kztti
klnbsg egy derkszg hromszg egyik befogjt hatrozza meg, a msik befog
100 mter.
3.48.4. Bvtse ki az elz programot gy, hogy a leghosszabb sk terlet hosszt, valamint
kezd s vg pontjnak pozcijt keresse meg! Sk terletnek szmt az, ahol a terep
pontjai sszefggen azonos magassgak.
3.49. Ritka vektor
3.49.1. Nemo kapitny almerl a Nautilus tengeralattjrval, hogy megvizsglja a tenger
lvilgt. Merls kzben a segdei minden tzedik mternl megszmoljk, hogy
mennyi halat ltnak, hogy ezt felhasznlhassk ksbbi kutatsaikhoz. A szmllsok
eredmnyt egy vektorban troljk el, ahol az i. komponens a 10*i mter mlyen
vgzett szmlls eredmnyt trolja. Sajnos mg nem ll rendelkezsre nagy memria
kapacits szmtgp, az eredmnyeket lyukkrtyra rjk. Megfigyeltk, hogy nagyon
gyakran nem ltnak egy halat sem, ezrt gy gondoltk, oly mdon troljk az
eredmnyeket, hogy ezt a tnyt kihasznljk s a ritka vektorok trolsi mdszerhez
folyamodtak, gy helyet takartottak meg, s az adatok feldolgozsa is gyorsabb. rjon
programot, amely egy ilyen ritka vektorokat kezel! A ritka vektorok olyan vektorok,
amelyek nagyon kevs nem 0 komponenst tartalmaznak. Ezeket clszer gy trolni,
hogy csak a nem 0 elemeket troljuk, azon vektoron belli indexvel. Ennek egyik
mdja, ha a (szm, index) prokat lncolt listban troljuk. A vektor dimenzija nincs
korltozva. Valstsa meg a kvetkez mveleteket:
Bellt(index, rtk): A vektor adott index elemt az adott rtkre lltja be. Ha az
rtk 0, akkor az elem nem troldik.
rtk(index): A mvelet visszaadja az adott index elem rtkt.
Trl: A mvelet nullza a teljes vektor tartalmt.
NemNullk: A mvelet visszaadja, hogy mennyi nem 0 elem van a vektorban.
Legutols: A mvelet visszaadja, hogy hnyas indexen tallhat a legutols nem 0
elem.
Megjelent: A mvelet kirja a kpernyre a teljes vektort egszen a Legutols
ltal meghatrozott elemig. A 0-kat is meg kell jelenteni.
3.49.2. Elfordulhat, hogy az elz vektoron bell az elemek nem j sorrendben kvetik
egymst. Pldul lehet, hogy elbb tallhat meg az 5-s index elem a listban, mint a
3-as. Implementlja a Rendez mveletet, amely az indexeknek megfelelen nvekv
sorrendbe rendezi a listn belli elemeket!
56 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.49.3. Bvtse ki az elz programot az sszeads s a szorzs mveletekkel! Az sszeads
kt ritka vektort ad ssze. gyeljen arra, hogy a 0 elemeket ne trolja el! A szorzs 2
ritka vektort szoroz ssze skalrisan.

4. Lncolt listk feladatai 57
Heckl Istvn, PE www.tankonyvtar.hu
4. Lncolt listk feladatai
4.1. Lista kt tmbbel
4.1.1. Ksztsen programot, amelyben egy (nem ciklikus) lncolt listt kt tmbbel
reprezentl! Az egyik tmb az elemek rtkeit, a msik a kvetkez elem indext
tartalmazza. Egsz vltoz tartalmazza a lista els elemnek az indext! Inicializlja a
tmbket a kvetkez rtkekkel: rtkek: {34, 12.55, 893.2, 2, 11.6, 47.5, 45.3},
indexek: {-1, 0, 4, 1, 6, 3, 5}! A kettes index elem a lista els tagja. rjon fggvnyt a
lista elemeinek listzshoz! rjon fggvnyt az utols elem trlshez, trlje egyenknt
az elemeket s minden trls utn listzza az elemeket! Hogyan kell mdostani a
programot, ha trls utn elem beszrsa kvetkezik?
4.1.2. rjon fggvnyt, amely a lista els elemt trli! rjon fggvnyt, amely ellenrzi, hogy
az tmb konzisztens-e, vagyis a benne lv indexek a megengedett tartomnyban
vannak-e, a start elemtl indulva nem jelentkezik kr!
4.1.3. Valstsa meg hasonl mdon a ciklikus listt! Listzskor lehessen megadni, hogy
honnan kezddjk a kirs!
4.2. Lista egy tmbbel
4.2.1. Ksztsen programot, amelyben egy (nem ciklikus) lncolt listt statikus tmbbel
reprezentl, gy, hogy a tmb rekordokat tartalmaz, amelyekben nv, letkor s a
kvetkez elem indexe adattag szerepel! rjon fggvnyt, amely a lista elejre fz be j
elemet! Az j rekord helyt a tmbben vletlen szm genertorral hatrozza meg a
kvetkez mdon: ltrehoz egy vletlen indexet; ha az azon indexhez tartoz rekord
kvetkez elem adattag rtke -2, akkor a krdses rekord nem tartalmaz hasznos
informcit vagyis nem hasznlt rekordrl van sz; egybknt nzznk meg egy msik
vletlen index elemet! (A mdszer htrnya, hogy ha nincs tbb szabad hely, akkor a
foglals vgtelen ciklusba kerl, a korrekt megolds az lenne, ha kln tartannk
nylvn a szabad helyeket.)
4.2.2. rjon fggvnyt a lista kiratshoz! Egyenknt adjon elemeket a listhoz s rja ki az
eredmny listt!
4.2.3. Mdostsa gy az elz programot, hogy jelezze, ha nem sikeres az elem hozzadsa,
mert betelt a trol tmb! Dinamikus tmbben trolja a listt, ha tmb betelne, akkor
foglaljon le egy nagyobb tmbt! Valstsa meg a lista vgre beszr fggvnyt!
4.3. Lista szerkezet
4.3.1. A karakteres kpernyn jelentsen meg egy 3 hossz, egyszeresen lncolt listt! A listt
kzvetlen rtkadsokkal hozza ltre, jelentse meg a listt reprezentl fej vltozt is!
58 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

4.1. bra: Lehetsges kpernykp
4.3.2. Hasonl mdon jelentse meg az oda-vissza lncolt listt!
4.4. Lncolt lista dinamikus rekordokkal
4.4.1. rjon programot, amely dinamikus struktrkkal valstja meg az egyszeresen lncolt
listt! Minden rekord trolja a kvetkez adatokat egy motorrl: nv, r, teljestmny!
Valstsa meg a beszrst az x. elem utn, a listzst s a listatrlst fggvnyekkel! Ha
nincs x darab eleme a listnak, akkor a lista vgre szrjon be! rszemmel trolja a
lista fejt! Adjon 4 elemet a listhoz, mindig a msodik elem utn!
4.4.2. Ksztsen fggvnyt adott sorszm elem trlsre!
4.4.3. rjon fggvnyeket, amelyek adott mezk alapjn keresnek meg elemeket! Legyen
olyan vltozat, amely megadja az els elfordulst, adott index elemtl tekintve az
els elfordulst, az sszes elfordulst! rjon fggvnyt, amely sorszm alapjn
felcserl kt elemet, adott tulajdonsg elemeket trl ki, fordtva jrja be a listt (s
rja ki az elemeit)!
4.5. Sablon
4.5.1. Ksztsen egy replgp osztlyt azonost, utasok, elz, kvetkez adattagokkal!
Ksztsen ktszeresen lncolt listt, sablon osztllyal! Trolja a lista elejt, vgt s az
aktulis elemet! Valstsa meg a kvetkez metdusokat: konstruktor, destruktor, adott
elem keresse, elem beszrsa aktulis elem el, aktulis elem trlse, aktulis mutat
mozgatsa relatv indexszel, aktulis elem referencijnak visszaadsa, elemszm
visszaadsa, kir opertor. Tesztelje a listt a replgp osztly felhasznlsval!
4.5.2. rjon metdust az aktulis mutat abszolt mozgatsra, adott sorszm elem trlsre,
adott objektum trlsre, a teljes lista trlsre, aktulis mutat utni beszrsra!
4.6. Lista
4.6.1. rjon programot, amely szmokat olvas be a billentyzetrl addig, amg a beolvasott
szm nem 0! A program fzze a beolvasott szmot egy egyszeresen lncolt lista vgre!
A -1 gpelse utn rja ki a kpernyre a lista tartalmt! Valstsa meg az add s print
fggvnyeket, valamint a lista felszabadtst!
Plda:
Type a number: 10
Type a number: 20
Type a number: 30
Type a number: -1
The list: 10 20 30
4. Lncolt listk feladatai 59
Heckl Istvn, PE www.tankonyvtar.hu
Type a number: 40
Type a number: 50
Type a number: -1
The list: 10 20 30 40 50
Type a number: 0
4.7. Prmszita
4.7.1. Krjnk be egy tetszleges egsz szmot (n), majd egy listba tegyk be 2-tl n-ig a
termszetes szmokat! Vegynk ki minden nem prm szmot a listbl! tlet: a lista
els eleme (2) prm, minden olyan szmot trlnk, amely oszthat ezzel a szmmal (az
els iterciban 2 kivtelvel az sszes pros szm trldik). A megmaradt elemek
kzl a kvetkez ismt prm, trljk ennek is minden tbbszrst. Ezt ismteljk
addig, amg a lista vgre nem rnk, ekkor rjuk ki a listt!
4.8. Halmazmveletek
4.8.1. Hozzunk ltre kt rendezett listt, majd ksztsk el a kt lista unijt, az eredmnyt az
els listban troljuk!
4.8.2. Uni helyett a kt lista metszett kpezzk!

60 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
5. A verem s sor adatszerkezetek feladatai
5.1. Verem osztly
5.1.1. Ksztsen egy verem osztlyt, amely statikus, 5 nagysg egsz tmbben trol
rtkeket! valstsa meg a kvetkez metdusokat: init, push, pop, isFull, isEmpty!
tlet: egyrtelmen definilja, hogy a verem mutat az els szabad elemre vagy az
utols hasznlt elemre mutat-e!
5.1.2. Valstsa meg a vermet dinamikus tmbbel! Ha betelt a tmb, foglaljon le egy nagyobbat
5.2. Verem
5.2.1. rjon programot, amely szmokat olvas be a billentyzetrl addig, amg a beolvasott
szm nem 0! Trolja a szmokat egy veremben, amit lncolt listval valstson meg. A
0 gpelse utn a program olvassa ki a szmokat a verembl, s rja a kpernyre!
Valstsa meg a push s pop fggvnyeket, valamint a lista felszabadtst!
Plda:
Type a number: 1
Type a number: 5
Type a number: 7
Type a number: 0
7
5
1
5.3. Sor
5.3.1. rjon programot, amely szmokat olvas be a billentyzetrl addig, amg a beolvasott
szm nem 0! Trolja ezeket egy sorban, amit lncolt listval valsts meg! A 0 gpelse
utn a program olvassa ki a szmokat a sorbl, s rja a kpernyre! Valstsa meg a
push s pop fggvnyeket, valamint a lista felszabadtst!
Plda:
Type a number: 10
Type a number: 43
Type a number: 2
Type a number: 5
Type a number: 0
10
43
2
5
5.4. Fordtott lengyelforma
5.4.1. Egy matematikai kifejezst felrhatunk gynevezett fordtott lengyelformban is.
Pldul a 3 + 4 kifejezs ebben az alakban gy nz ki: 3 4 +. Fordtott lengyelformban
nincs szksg zrjelekre, s a mveletek precedencijra sem kell gyelni, mert azt
mr figyelembe vettk akkor, amikor meghatroztuk ezt a formt. A fordtott
5. A verem s sor adatszerkezetek feladatai 61
Heckl Istvn, PE www.tankonyvtar.hu
lengyelformban lv kifejezs egy verem segtsgvel rtkelhet ki. Balrl jobbra
olvassuk a kifejezst, ha szm kvetkezik, akkor azt berakjuk a verembe, ha mveleti
jel, akkor kivesznk a verembl 2 elemet, elvgezzk rajtuk a mveletet, majd az
eredmnyt visszahelyezzk a verembe. A (2 + 5) * 3 - 9 / (2 + 1) kifejezs fordtott
lengyelformban: 2 5 + 3 * 9 2 1 + / -. Az algoritmus az albbi tblzatban lv
lpseket hajtja vgre a kifejezs kirtkelshez. rjon programot, amely beolvas egy
matematikai kifejezst fordtott lengyel formban, majd az ismertetett mdszer szerint
megoldja azt!
Lps Verem
tartalma
Kifejezs Mvelet
0 2 5 + 3 * 9 2 1 + / -
1 2 5 + 3 * 9 2 1 + / - Verembe(2)
2 2 5 + 3 * 9 2 1 + / - Verembe(5)
3 7 3 * 9 2 1 + / -
a = Verembl
b = Verembl
Verembe (b + a)
4 7 3 * 9 2 1 + / - Verembe(3)
5 21 9 2 1 + / -
a = Verembl
b = Verembl
Verembe(b*a)
6 21 9 2 1 + / - Verembe(9)
7 21 9 2 1 + / - Verembe(2)
8 21 9 2 1 + / - Verembe(1)
9 21 9 3 / -
a = Verembl
b = Verembl
Verembe(b+a)
10 21 3 -
a = Verembl
b = Verembl
Verembe(b/a)
11 18
a = Verembl
b = Verembl
Verembe(b-a)
5.5. Vrlista
5.5.1. Egy fvrosi hivatalban az gyfeleknek rendszerint vrakozni kell. Minden jonnan
rkez szemly kap egy azonostt s az embereket ezen azonostk alapjn szltjk. A
kiszolgls rkezsi sorrendben trtnik. rjon programot, amely segt a hivatal
szemlyzetnek a kvetkez kiszolgland gyfl azonostjnak megllaptsban!
Valstsa meg a sor adatszerkezetet, ahol a beszrs mvelet ltrehoz egy j azonostt,
kirja a kpernyre s hozzadja a sorhoz! A kivesz mvelet kiveszi a sorbl egy elemet
s az azonostt kirja a kpernyre. Men segtsgvel lehessen vlasztani a beszrs
s a kivesz mveletek kztt!
5.5.2. Elfordulhat, hogy egyszerre tbb embert tudnak kiszolglni. Bvtse ki a programot az
N_kivesz mvelettel, amely N darab elemet vesz ki a sorbl s kirja a megfelel
azonostkat!
62 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
5.6. Nyomtatk
A fvrosi Knyvktszeti- s Borszati Fiskola Szltermesztsi Tanszkn egy hlzati
nyomtatt hasznl mindenki. Minden nyomtatsi feladat bekerl egy nyomtatsi sorba. A
tanszken az emberek nem egyenrangak, a fontossgi sorrendet az egyes szemlyeknek a
szervezeti hierarchin belli pozcija szabja meg. A kvetkez fokozatokat klnbztetjk meg:
tanszkvezet, professzorok, docensek, adjunktusok s tanrsegdek. Pldul, ha a nyomtatsi sor
elejn van 2 feladat docensektl, majd utna 3 tanrsegdektl, akkor, ha egy adjunktus elindt egy
nyomtatst, akkor az a docensek feladatai utn, a tanrsegdek eltt jelenik meg a sorban. Az
azonos hierarchia szinten lv emberek nyomtatsa rkezsi sorrend alapjn trtnik
5.6.1. rjon programot, amely kezeli a nyomtatsi sort a fenti precedenciknak megfelelen!
Valstsd meg Beszrs s Kvetkez mveleteket! Beszrsnl a dokumentum
azonostjt s a szemly rangjt kell megadni. Minden nyomtats elindtsa utn 45%
valsznsggel rgtn elkszl egy nyomtats.
5.6.2. Bvtse ki a programot gy, hogy minden nyomtats eltt egy szemlyhez tartoz kdot
kell megadni! Csak akkor lehet nyomtatni, ha a kd helyes. A kdbl kvetkezik a
szemly rangja is. Minden nyomtats elindtsa utn jelentse meg a nyomtatsi sort!
5.7. Pascal hromszg
5.7.1. lltsuk el a Pascal hromszget a k-dik sorig, sor adatszerkezetet hasznlva! tlet:ha
az i-dik sora megvan a Pascal hromszgnek, akkor abbl megkapjuk a i+1-edik sort a
kvetkez kpen. Vegyk ki az utols elemet a sorbl s troljuk el, adjuk hozz az j
utols elemet, majd rakjuk be a sor elejre. Az elz mveleteket sszesen (i-1)-szer
hajtsuk vgre, ezutn rakjuk be a sor elejre az 1 elemet. Plda: (1 3 3 1); utols elem
ki -> (1 3 3); sszeads, lista elejre fzs -> (4 1 3 3); utols elem ki -> (4 1 3);
sszeads, lista elejre fzs -> (6 4 1 3); utols elem ki -> (6 4 1); sszeads, lista
elejre fzs -> (4 6 4 1); 1-es elem befzse a lista elejre -> (1 4 6 4 1).
5.8. Periodikus ads
5.8.1. Egy rdiad periodikusan ismtli ugyanazt az adst, minden ads vgn egy specilis
jelet ad (#). Az adssorozat egy szekvencilis karakter tmbben van, dntsk el egy sor
adatszerkezetet hasznlva, hogy volt-e hiba valamelyik adsban! Hiba az adsban: nem
mindig ugyanazt a jelsorozatot adta le az ad.
5.9. Zrjelezs
5.9.1. Krjnk be egy kifejezst, ami tbb nyit s zrjelet tartalmaz! Verem segtsgvel
rjuk ki az sszetartoz zrjelprok indexeit, s kzben dntsk el, hogy helyes-e a
zrjelezs!

6. Binris fk feladatai 63
Heckl Istvn, PE www.tankonyvtar.hu
6. Binris fk feladatai
6.1. Binris fa szlvel
6.1.1. Hozzon ltre struktrt a binris fa csompontja szmra! Hasznljon szl mutatt s
egy egsz tpus adattagot! Hozzon ltre 8 struktra vltozt s lltsa be gy a
mutatkat, hogy kialaktsa az albbi adatszerkezetet! rjon ment, amelynek a
segtsgvel a fn mozoghat balra, jobbra, visszafele s kilphet! rja ki mindig az
aktulis elem egsz adattagjt s hogy vannak-e gyerekei! Ha olyan irnyba trtnne a
mozgs, ahol nincs csompont, akkor nem vltozik az aktulis mutat.
11
13 9
66
2
8
23
7

bra: Megvalstand szerkezet
6.1.2. Az egsz adattag mellet mg legyen sztring s lebegpontos szm tpus adattag is! A
menben legyen lehetsg az egyes adattagok megvltoztatsra!
6.2. Fabejrsok
6.2.1. Hozzon ltre struktrt a binris fa csompontja szmra! Ne hasznljon szl mutatt,
de legyen egy egsz tpus adattag! Hozzon ltre 8 struktra vltozt s lltsa be gy a
mutatkat, hogy kialaktsa az albbi adatszerkezetet! Valstsa meg a preodrer, inorder
s postorder fabejrsokat!
7
4 9
1 5
2
8
3

bra: Megvalstand szerkezet
64 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
6.3. Binris keresfa
6.3.1. Troljon adatokat egerekrl binris keresfban r szerint rendezve! A troland
adatok: r - int, gyrt - statikus sztring, infra - bitmez, madzag hossz vagy infra
hattv - lebegpontos. Ne hasznljon szl mutatt! Trolja a fa gykert rszemmel!
Az rszem kulcsmezjnek maximlisnak kell lennie! Valstsa meg a kvetkez
fggvnyeket: csompont megjelentse, fa megjelentse, fa felszabadtsa, csompont
beszrsa! Teszteljk a programot!
6.3.2. Mdostsa gy a programot, hogy az rszemben a legkisebb kulcs rtket troljuk! A
billentyzetrl krje be az j csompont tulajdonsgait! Az rszem helyett mutatval
reprezentljuk a ft! Hasznljon szl mutatt is!
6.4. Csaldfa
6.4.1. Az input fjl egy csaldfrl tartalmaz informcikat. Minden emberhez egy darab st
rendel. rjon programot, amely beolvassa a csaldft a fjlbl, a billentyzetrl pedig
bekr egy nevet! Ezutn a program rja ki a kpernyre a megadott szemly
gyerekeinek a nevt s letkort (az aktulis v 1436), vagy az vet, amikor meghaltak!
Ha a megadott embernek nincs gyereke, vagy nem ltezik, akkor a program ennek
megfelel zenetet rjon ki a kpernyre! Hasznljon dinamikus tmbket!
Az input formtuma:
NameString Number1 Number2 Number3
ahol
NameString: A szemly neve, egy sz szkz nlkl.
Number1: A szemly szletsi ve
Number2: A szemly hallnak ve (ha ez a szm -1, a szemly l)
Number3: A szemly gyerekeinek szma

Az input faszerkezet szeren trolja a szemlyeket. Ha valakinek kt gyereke van, akkor elszr az
els gyermek sort rjuk le, aztn felsoroljuk az els gyermek leszrmazottjt s csak utna jn a
msodik gyerekhez tartoz sor. A bemeneti fjl tabullsa nem ktelez.
Plda:
Fosco 1264 1360 3
Dora 1302 1406 0
Drogo 1308 1380 1
Frodo 1368 -1 0
Dudo 1311 1409 1
Daisy 1350 -1 0

Fosco 1264-ben szletett, s 1360-ban halt meg. 3 gyermeke volt, Dora, Drogo s Dudo. Drogo fia
volt Frodo, aki 1368-ban szletett, s mg letben van. Dora 104 vet lt.

Kimenet: (A Fosco nevet gpeltk be)
Name: Fosco
Children of Fosco:
*********************************
Dora, lived for 104 years
Drogo, lived for 72 years
Dudo, lived for 98 years
6. Binris fk feladatai 65
Heckl Istvn, PE www.tankonyvtar.hu
6.5. Matematikai kifejezsek kirtkelse
6.5.1. rjon programot, amely kirtkel egy egyszer matematikai kifejezst! A kifejezsek
lebegpontos szmokat, illetve ngy matematikai opertort tartalmazhatnak: sszeads
(+), kivons (-), szorzs (*), oszts (/). A kifejezs nem tartalmaz zrjeleket. A
kifejezst fjlbl olvassa be! A program a beolvasott matematikai kifejezst s annak
eredmnyt rja ki a kpernyre! Figyeljen az opertorok kirtkelsi sorrendjre!
Pldul 1 + 2 * 3 = 7 s nem 9.
Az input fjl formtuma:
Els sor: Az operandusok szma.
Msodik sor: A matematikai kifejezs. A szmok s opertorok egy-egy szkz karakterrel vannak
elvlasztva.
Plda bemenet:
6
2 + 3 * 54 - 64 / 10 + 60
Kimenet:
2 + 3 * 54 - 64 / 10 + 60 = 217.6
6.6.Binris fa feladatok
6.6.1. rjon programot, amely egy tmb elemeibl kszt binris keresft, ezutn hatrozza
meg, hny cscsa, illetve hny levele van a fnak! A binris keresfa olyan
adatszerkezet, amelyben minden elemnek kt mutatja van, egy jobb, illetve egy bal. A
fba elsknt belerakott elem a gykr, ezutn minden elemet a kvetkezkpp
helyeznk el. Kiindulunk a gykr elemtl. Ha a beszrni kvnt elem kisebb, mint az
aktulis, akkor balra megynk tovbb a fban, ha nagyobb, akkor jobbra. Egszen addig
haladunk gy a fban, amg egy res helyet tallunk, ide beszrjuk az kvnt elemet.
6.6.2. rjon fggvnyeket a kvetkez funkcik megvalstsra; fa magassga (a gykr-
levl tvolsgok kztt a legnagyobb), maximlis rtk meghatrozsa, gykrhez
legkzelebb es szint meghatrozsa, amin mr van levele a fnak! Levl: olyan cscs a
fban, aminek nincsen se bal, se jobb gyereke.
6.6.3. rjon programot, amely eldnti kt frl, hogy azonos alakak-e!

66 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
7. Grf feladatok
7.1. Tzoltk
7.1.1. Egy nagyvros kzepn tallhat a tzolt lloms. Sajnos gyakran megesik, hogy a tz
helysznre tart tzolt autk nem azon az tvonalon haladnak, amerre a leghamarabb
kirnnek, mivel a sofrk nem kpesek a legrvidebb utat meghatrozni. rjon
tvonaltervez programot, amely egy mtrixban trolt thlzat alapjn megtervezi a
legrvidebb tvonalat a tzolt lloms s a tz helyszne kztt! tlet: hasznljon
Dijkstra algoritmust!
7.2. Bolygkzi futrszolglat
A Bolygkzi Kzbest Vllalat klnbz bolygk kztt bonyolt le szlltsokat. Mivel a
tvolsgok hatalmasak, ezrt a kzlekedst trkapukon keresztl oldjk meg. Az egyes bolygk
kzelben fregjrat nylsok helyezkednek el, minden jrat egy msik bolyg kzelben r vget.
A kzlekeds eme jratrendszerek belsejben zajlik. A jratok nylsai a kzeli bolyg
kormnyzatnak a tulajdonban llnak, gy a jratba val belpsrt djat szednek. A jrat
hasznlatrt fizetend sszeg fgg a belpsi pontot birtokl kormnyzattl, valamint a cl
llomstl (a npszerbb clllomsok fel tart jrmveket jobban megsarcoljk). Adott egy
csillagtrkp, amelyen feltntettk, hogy mely bolygk kztt ltezik fregjrat, s az egyes
jratokrt mekkora djat kell fizetni. A trkp adjacencia mtrixban van trolva, ahol -1 jelzi azt, ha
kt bolyg kztt nincs kzvetlen jrat, egybknt pedig az egyes tarifkat troljuk a mtrix
celliban.
7.2.1. Ksztsen programot, amely beolvassa a csillagtrkpet egy fjlbl, majd hatrozza
meg, hogy legolcsbban mekkora sszegrt lehet szlltani a felhasznl ltal megadott
kt bolyg kztt! Adja meg a legolcsbb thoz tartoz tvonalat is! tlet: hasznljon
Dijkstra algoritmust!
7.2.2. Krjen be egy bolyg sorszmt, majd hatrozza meg, hogy a fregjratokon keresztl
hny bolyghoz lehet onnan eljutni!
7.2.3. Hatrozza meg, hogy hny darab komponens tallhat a csillagtrkpen! Az egy
komponensben lv bolygk kztt ltezik tvonal, kt kln komponensben lv
bolyg kztt nem ltezik. Adja minden komponensben, az ott tallhat bolygk
szmt!
7.3. Ozisok
7.3.1. A Szahara egyik szegletben 11 ozis tallhat. Nem mindegyik kztt van kzvetlen
t s az utak sokszor kacskaringsak, hogy elkerljk a futhomokot s ms
veszlyeket. 10 beduin trzs l kln ozisokban, a 11., a szent ozis lakatlan. A
trzsek egyszer csak szreveszik, hogy mindegyikk ozisa a kiszrads szln ll.
sszegyltek ht, hogy megoldst talljanak a problmra. A szent ozisban annyi vz
van, amely kpes elegend vzzel elltni a trzseket. Megllapodnak abban, hogy
kzsen ptenek egy csvezetk rendszert az utak mellett, amelyen keresztl elegend
vzhez jut minden trzs. Ismerjk az ozisok kztti utak tvolsgt. rjon programot,
amely megtervez egy, az ozisokat sszekt cshlzatot gy, hogy a lehet
legkevesebb cs felhasznlsval minden kiszrad ozis vzhez juthasson. A csvek
7. Grf feladatok 67
Heckl Istvn, PE www.tankonyvtar.hu
kapacitsa elg nagy, teht az egyszerre szlltand vz mennyisgvel nem kell
foglalkozni. tlet: hasznljon Prim algoritmust!
7.4. Srhlzat
A Ktfark Kutyaprt megnyerte a vlasztsokat, gy gretkhz hven az ivvz hlzat
mell ingyen sr hlzatot alaktanak ki. Mindenkinek persze nem jut az ingyen srbl, de az v
egy napjn lelltjk a vzszolgltatst s a vzvezetkeken keresztl egy szerencss kisorsolt
vrosban megindul a srszolgltats. A vrosok kztti vzvezetknek ismert a szlltsi
kapacitsa, valamint hogy az egyes vezetkek mely vrosokat ktnek ssze. A hlzat egyik
csompontja a srgyr.
7.4.1. rjon programot, amely megmondja, hogy maximlisan mennyi srt lehet tovbbtani a
srgyrbl a kisorsolt vrosba, ehhez mely vezetkeket kell felhasznlni s, hogy ezek a
vezetkek milyen mrtkben lesznek kihasznlva! A program fjlbl olvassa be a
vezetkhlzatot s a felhasznltl krdezze meg, hogy hol van a srgyr s melyik a
kisorsolt vros! tlet: hasznljon Ford s Fulkerson algoritmust!
7.4.2. .Hatrozzuk meg, hogy ha csak egy vrosban lehet srgyr (a helyt nem ktjk ki),
akkor legfeljebb hny vrost lthatunk el itallal? Ez azrt fontos, mert a vezetkhlzat
nem kt ssze minden vrost.
7.4.3. rjon fggvnyt, amely meghatrozza, hogy egy adott csompontbl hova lehet
eljuttatni a legnagyobb mennyisg srt, s mekkora ez a mennyisg!
7.5. Pros grf
7.5.1. Dntsk el egy grfrl, hogy pros-e, ehhez segtsgnek hasznljunk szomszdossgi
mtrixot s szlessgi keresst! A szlessgi keress a grf egy adott cscsbl
kiindulva bejrjanak szomszdjait, ezutn azok szomszdjait s gy tovbb. Az
algoritmus implementcijban segthet, ha a nem megltogatott cscsokat egy sor
adatszerkezetbe rakjuk, a megltogatni kvnt cscsokat pedig kivessznk ebbl a
listbl s belerakjuk egy tmenetibe, gy az algoritmust addig kell futtatni, mg van
kivehet elem a sorbl.
7.6. Belmann-Ford algoritmus
7.6.1. Valstsuk meg a Bellman-Ford algoritmust egy grfon! Az algoritmus egy irnytott
grf adott pontjtl keresi meg a minimlis kltsg utakat a grf tbbi pontjba.
Elszr az egy, majd a kett l hossz legrvidebb utakat keresi meg s gy tovbb. Ha
a grf negatv krt tartalmaz, az algoritmus nem ad vissza j rtket.
7.6.2. Szmtsuk ki egy fa tmrjt! Egy fa tmrje alatt a fa brmely kt cscsa kztt fut
legrvidebb utak kzl a leghosszabbat rtjk. tlet: Ha lefuttatjuk a fa minden
pontjra a Belmann-Ford algoritmust, akkor ebbl mr csak a legkisebb elemet kell
kivlasztani.
7.6.3. Adott egy valuta tvltsi tblzat (adjacencia mtrix). x valutt y-ra szeretnnk vltani,
keressk meg azt az tvltsi sorozatot, amelyben a legtbb y valutt kapjuk. Nem
biztos, hogy a direkt tvlts a legjobb. Pl.: 1 dollrrt kapunk 2 eurt, azonban 1
dollrrt kaphatunk 6 frankot is, 1 frankrt fl dollrt, gy a dollr frank - eur lesz a
legjobb tvlts. Az tvltsi tblzat ftlja csupa egyes, hiszen 1 dollr tvltva
68 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
dollrra 1 dollrt kapunk. A ftlra szimmetrikusan pedig egyms reciprokjai kell,
hogy szerepeljenek, mert ha 1 eur = 2 dollr, akkor 1 dollr = 1/2 eur.
7.7. Kruskal algoritmus
7.7.1. Valstsa meg a Kruskal algoritmust! Trolja halmazban az pl fesztfa cscsait!
Hasznlja az UNI, HOLVAN halmazmveleteket annak eldntsre, hogy egy j l
felvtele okoz-e krt a fesztfban! tlet: Az algoritmus elejn a grf minden pontja
egy nll halmazt jelent. A HOLVAN mvelet megadja, hogy egy elem, melyik
halmazban tallhat, az UNI mvelet kt halmazt egyest. Ha egy let akarunk
hozzadni a fesztfhoz, akkor meg kell vizsglni, hogy az l kt pontja ugyanabba a
halmazba tartozik-e. Ha igen, akkor az l felvtele krt okozna, gy a kvetkez
legkisebb sly lt kell vizsglni. A halmazokat (nem binris) fkkal reprezentljuk. Az
UNI mvelet kt ilyen ft egyest oly mdon, hogy az els fa a gykere a msodik fa
gykernek egy j gyereke lesz. A HOLVAN mvelet megadja a fa gykert.
7.7.2. A minimlis kltsg fesztfa helyett keresnk maximlis kltsgt! Egy
kommunikcis hlzat tartalmazza a szmtgpeket s az azok kztti ktirny
kapcsolatokat. Mindegyik kapcsolathoz svszlessg tartozik. Brmely, kt gpet
sszekt hlzatrsz svszlessge alatt az egyes vezetkszakaszok svszlessgnek
minimumt rtjk. Ha kt gp kztt tbb ton is ltesthet kapcsolat, akkor az
sszekttets svszlessge ezek kzl a maximum. A teljes hlzat svszlessge alatt
az azt alkot gpek kztti svszlessgek minimumt rtjk. Ha a grf nem
sszefgg, akkor 0 a svszlessg. rjunk programot, amely beolvassa a hlzat
adatait, majd meghatrozza a svszlessgt!

8. Rendezsi feladatok 69
Heckl Istvn, PE www.tankonyvtar.hu
8. Rendezsi feladatok
8.1.Tmbrendezs
8.1.1. rjon fggvnyt, amely bubork illetve minimum kivlasztsos mdszerrel rendez egy
tmbt! rjon segdfggvnyeket a minIndex, swap, print (tmb kirs) feladatokra!
8.1.2. Ismerje meg s valstson meg a kvetkez rendez fggvnyek kzl kettt! Beszr
rendezs, shell rendezse, radix rendezs, shaker rendezs, heap rendezs, comb
rendezs.
8.2. Rekurzv fggvnyek
8.2.1. Valstsa meg a gyorsrendezst! Mindig rja ki, hogy milyen mlyen van a rekurziban
statikus vltoz segtsgvel, s hogy mely rsztmbt rendezi ppen! A kirsokat a
rekurzi mlysge alapjn tabullja!
8.2.2. Valstsa meg a Fibonacci sort rekurzvan! Az elz program szerint tabullssal
jellje, hogy milyen mlyen van a rekurziban!
8.3. Nvsor
8.3.1. Feladat: rjon programot, amely abc sorrendbe rendez neveket! Krje be, hogy hny
nevet akar rendezni, ezutn krje be a neveket! Rendezze a neveket bubork
rendezssel! tlet: hasznlja az stricmp fggvnyt!
8.3.2. Mdostsa gy a programot, hogy a klnbz eltagok (Dr., prof., PhD., ) ne
befolysoljk a sorrendet!
8.4. Rendezett lncolt lista
8.4.1. Valstson meg egy ktszeresen lncolt listt, amely ID alapjn cskken sorrendben
tartalmazza a rekordokat! Hasznljon rszemeket a lista kt vgn! A listt egy
struktra reprezentlja, amely az rszemeket tartalmazza! A lista elem tartalmazza az
elre, htra mutat mezket s egy mutatt az adat struktrra! Az adat struktra
tartalmazza kvetkez mezket: ID, mret, szrmazsi hely.
8.4.2. Egsztse ki a lista struktrt egy egsszel, amely az elemek szmt mutatja a listban!
Mdostsa a fggvnyeket, hogy azok kezeljk az j adattagot!
8.5. Kupacrendezs
8.5.1. Valstsa meg a kupacrendezst! A kupac legyen tmbbel reprezentlva! Minden
tmbelem mutasson egy fejhallgat tpus struktrra, amelynek az adattagjai:
azonost - egsz, nv - sztring, r - lebegpontos. rja meg a kvetkez fggvnyeket:
egy fejhallgat adatainak kirsa, kupac kirsa (minden fejhallgat kln sorba, az
azonos mezk egy oszlopban legyenek), a mutat tmb kt elemnek felcserlse,
felszivrog, kupacpts, kupacrendezs!
70 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
8.6. Szavak rendezse
8.6.1. rjon programot, amely szavakat rendez nvekv sorrendbe az strcmp fggvny
hasznlata nlkl! A szavak csak nagybetkbl llnak. A program olvassa be fjlbl a
szavakat, s rja ki azokat a kpernyre nvekv sorrendben. Ha egy sz megegyezik
egy msik, hosszabb sz elejvel, akkor a hosszabb sz szerepel ksbb. Pldul: SO <
SOAP. A szavak maximlis hossza 15 karakter. Hasznljon dinamikus tmbket a
szavak trolshoz! A sorrendnl a betk ASCII kdja szmt.
Az input fjl formtuma:
Els sor: A szavak szma.
A tbbi sor egy-egy szt tartalmaz.
Plda bemenet:
7
WARIOR
APPLE
SZOKOZSHIP
BOOK
SZOKOZ
PHISIC
LIMON
Kimenet:
Read words:
1.: WARIOR
2.: APPLE
3.: SOAP
4.: BOOK
5.: SO
6.: PHISIC
7.: LIMON

***************
Sorted words :
1.: APPLE
2.: BOOK
3.: LIMON
4.: PHISIC
5.: SO
6.: SOAP
7.: WARIOR
8.7. Emlkeztetk
8.7.1. James nagyon feledkeny, ezrt emlkeztetket szokott rni magnak. Egy emlkeztet
egy dtumot tartalmaz (v, hnap, nap), egy idpontot (rt), s egy emlkeztet
kulcsszt. Az emlkeztetk sszekeveredtek, ezrt programot kell rni azok
rendezsre. Az emlkeztetket fjlbl olvassa be! rja ki a kpernyre a rendezett
emlkeztetsorozatot! Trolja az emlkeztetket struktrban, illetve dinamikus
tmbkben!
Az input fjl formtuma:
Els sor: az emlkeztetk szma.
8. Rendezsi feladatok 71
Heckl Istvn, PE www.tankonyvtar.hu
A tovbbi sorok az emlkeztetket troljk a kvetkez formtumban:
v Hnap Nap ra Kulcssz
Az v, hnap, nap s ra rtkei pozitv egszek. A sz maximlis hossza 20 karakter. A sorokban
az adatok szkz karakterekkel vannak elvlasztva.
Plda bemenet:
2
2008 11 20 12 Bank
2008 10 16 16 Dentist
Kimenet:
Year: 2008
Month: 10
Day: 16
Hour: 16
Dentist
Year: 2008
Month: 11
Day: 20
Hour: 12
Bank


72 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
9. Megoldsok
2.1.1.
#include <stdio.h> /* egyszeru feltetel */
int main() {
float result; // lebegopontos valtozo
printf("result=");
_flushall(); // buffer urites
scanf("%f", &result); // szam bekerese
if (result>50) { // feltetel
printf("Passed\n");
} else {
printf("Failed\n");
}
return 0;
}
2.1.2.
#include <stdio.h> /* egyszeru feltetel */
int main() {
float result; // lebegopontos valtozo
printf("result=");
_flushall(); // buffer urites
scanf("%f", &result); // szam bekerese
if (result>50) { // feltetel
printf("Passed\n");
} else {
printf("Failed\n");
}
return 0;
}
2.2.1.
#include <stdio.h>
int main() {
printf(" |a |b |c |d |e |f |g |h |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 1| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 2| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 3| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 4| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 5| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 6| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 7| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
printf(" 8| | | | | | | | |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
return 0;
}
9. Megoldsok 73
Heckl Istvn, PE www.tankonyvtar.hu
2.2.2.
#include <stdio.h>
#define SIZE 8
int main() {
int id;
printf(" |a |b |c |d |e |f |g |h |\n");
printf(" -|--|--|--|--|--|--|--|--|\n");
for (id = 0; id < SIZE; id++) {
printf(" %d| | | | | | | | |\n", id + 1);
printf(" -|--|--|--|--|--|--|--|--|\n");
}
return 0;
}
2.2.3.
#include <stdio.h>
#define SIZE 8
int main() {
int id1, id2;
printf(" |");
for (id1 = 'a'; id1 < 'a'+SIZE; id1++) {
printf("%c |",id1);
}
printf("\n -|");
for (id2 = 0; id2 < SIZE; id2++) {
printf("--|");
}
for (id1 = 0; id1 < SIZE; id1++) {
printf("\n %d|", id1+1);
for (id2 = 0; id2 < SIZE; id2++) {
printf(" |");
}
printf("\n -|");
for (id2 = 0; id2 < SIZE; id2++) {
printf("--|");
}
}
printf("\n");
return 0;
}
2.3.1.
#include <stdio.h>
int main() {
int a, b;
char decision;
printf("Program to calculate the area or perimeter of a
rectengular.\n");
printf("a=");
scanf("%d", &a);
printf("b=");
scanf("%d", &b);
printf("Would you like to calculate area (a) or perimeter (p) ? ");
scanf("%c", &decision);
if (decision=='a') {
printf("The area of the rectengular is: %d", a*b);
}
else {
printf("The perimeter of the rectengular is: %d", (a+b)*2);
74 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
return 0;
}
2.3.2.
#include <stdio.h>
int main() {
float a, b;
char figure, property;

printf("Program to calculate the area or perimeter of a rectengular
or square.\n");
printf("Calculate rectengular (r) or square (s) ");
scanf("%c", &figure);
if (figure=='r') {
printf("a=");
scanf("%f", &a);
printf("b=");
scanf("%f", &b);
printf("Would you like to calculate area (a) or perimeter (p) ?
");
scanf("%c", &property);
if (property=='a') {
printf("The area of the rectengular is: %f", a*b);
}
else {
printf("The perimeter of the rectengular is: %f", (a+b)*2);

}
} else {
printf("a=");
scanf("%f", &a);
printf("Would you like to calculate area (a) or perimeter (p) ?
");
scanf("%c", &property);
if (property=='a') {
printf("The area of the square is: %f", a*a);
}
else {
printf("The perimeter of the square is: %f", a*4);
}
}
return 0;
}
2.3.3.
#include <stdio.h>
#include <math.h>
int main() {
float a, b; //oldalak
char figure, prop; //figura - milyen alakzat lesz, prop - teruletet
vagy keruletet akarok szamolni

printf("Program to calculate the area or perimeter of a rectengular,
square or triangle.\n");
printf("Calculate rectengular (r) or square (s) or triangle (t)");
scanf("%c", &figure);
if (figure == 'r' || figure == 'R') {
printf("a= ");
9. Megoldsok 75
Heckl Istvn, PE www.tankonyvtar.hu
scanf("%f", &a);
if (a < 0) {
printf("This must be a positive value!\n");
return 1;
}
_flushall();
printf("b= ");
scanf("%f", &b);
if (b < 0) {
printf("This must be a positive value!\n");
return 1;
}
_flushall();
printf("Would you like to calculate area (a) or perimeter (p) ?
");
scanf("%c", &prop);
if (prop == 'a') {
printf("The area of the rectengular is: %f", a*b);
}
else {
printf("The perimeter of the rectengular is: %f", (a+b)*2);

}
}
else if (figure == 's' || figure == 'S') {
printf("a= ");
scanf("%f", &a);
if (a<0) {
printf("This must be a positive value!\n");
return 1;
}
_flushall();
printf("Would you like to calculate area (a) or perimeter (p) ?
");
scanf("%c", &prop);
if (prop == 'a') {
printf("The area of the square is: %f", a*a);
}
else {
printf("The perimeter of the square is: %f", a*4);
}
}
else if (figure == 't' || figure == 'T') {
printf("a=");
scanf("%f", &a);
if (a<0) {
printf("This must be a positive value!\n");
return 1;
}
_flushall();
printf("Would you like to calculate area (a) or perimeter (p) ?
");
scanf("%c", &prop);
if (prop == 'a') {
printf("The area of the trianegle is: %f", a*a*sqrt(3)/4);
}
else {
printf("The perimeter of the triangle is: %f", a*3);
}
76 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
else {
printf("Incorrect type of shape!\n");
return 1;
}
return 0;
}
2.4.1.
#include <stdio.h> /* egyszeru ciklus */
int main() {
int idxI; // egesz valtozo letrehozasa
for(idxI = 0; idxI < 10; idxI = idxI + 1) {
printf(" idxI is %d\n", idxI); // kiirs
}
return 0;
}
2.4.2.
#include <stdio.h> /* egyszeru ciklus */
int main() {
int idxI; // egesz valtozo letrehozasa
for(idxI = 60; idxI >= 40; idxI = idxI - 2) {
printf(" idxI is %d\n", idxI); // kiirs
}
return 0;
}
2.5.1.
#include <stdio.h>
int main() {
int idxA, idxB, idxC, size=1000;
for(idxA = 0; idxA < size; idxA++) {
for(idxB = 1; idxB < size; idxB++) {
for(idxC = 1; idxC < size; idxC++) {
// ...
}
}
}
return 0;
}
2.5.2.
#include <stdio.h>
int main() {
int idxA, idxB, idxC, size=1000;
int a, b = 2364, c = 9754;
for (idxA = 0; idxA < size; idxA++) {
for (idxB = 1; idxB < size; idxB++) {
for (idxC = 1; idxC < size; idxC++) {
a = b + c;
}
}
}
return 0;
}
2.6.1.
#include <stdio.h>
9. Megoldsok 77
Heckl Istvn, PE www.tankonyvtar.hu
int main() {
int id;
unsigned int age;
char sex, name[200];
float weight;
double accountBalance;

printf("id=");
scanf("%d", &id);
printf("age=");
scanf("%u", &age);
_flushall();
printf("sex=");
scanf("%c", &sex);
printf("weight=");
scanf("%f", &weight);
printf("account balance=");
scanf("%lf", &accountBalance);
printf("name=");
scanf("%s", name);
printf("\nYour data!\n");
printf("id=%d\n", id);
printf("age=%u\n", age);
printf("sex=%c\n", sex);
printf("weight=%f\n", weight);
printf("account balance=%lf\n", accountBalance);
printf("name=%s", name);
return 0;
}
A megadott s a kirt rtk lebegpontos rtkeknl klnbzhet, ha a megadott szmot nem
lehet pontosan brzolni az adott tpussal. Pl.: 32.11 helyett 32.110001, 234.33 helyett 234.330002.
2.6.2.
#include <stdio.h>
int main() {
const float a=3.14;
char dir;
printf("const float a=%f\n", a);
printf("Select direction! (1/2)\n");
scanf("%c", &dir);
if (a=='1') {
char a[200]= "Maroknyi szekely porlik, mint a szikla";
printf("string a=%s\n", a);
} else {
unsigned long int a=456789;
printf("unsigned long int a=%lu\n", a);
}
return 0;
}
2.7.1.
#include <iostream>
using namespace std;

int main ()
{
int direction;

78 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
cout << "Choose a direction: (1) const float, (2) char [200], (3)
unsigned long int" << endl;
cin >> direction;

if (direction==1) {
const float a=12.345;
cout << "a=" << a << endl;
}
if (direction==2) {
char a[200]=test123;
cout << "a=" << a << endl;
}
if (direction==3) {
unsigned long int a=98765;
cout << "a=" << a << endl;
}
if (direction<1 || direction>3) {
cout << "The direction value is incorrect" << endl;
}
return 0;
}
2.8.1.
#include <stdio.h>
int main() {
float a=12.45, b=-234.1, c=57967.2, d=134567;
printf("%+7.2f\n", a);
printf("%7.1f\n", b);
printf("%+8.1f\n", c);
printf("%+6.0f\n", d);
return 0;
}
2.8.2.
#include <stdio.h>
int main() {
int a = 235, c = 26, d = 2*1+11*16+10*16*16;
float b = -12910;
float e = 0.00164;

printf("%+6d\n", a);
printf("%12.3E\n", b);
printf("%05d\n", c);
printf("%#X\n", d);
printf("%.2e\n", e);
return 0;
}
2.9.1.
#include <stdio.h>
int main() {
const int size=5;
double array[]={3.456, 45697.678, -659.23, -0.0000965, 6.0000001};
int idxI, points=0;
char choice;
printf("How do you think the %%g will display the next numbers?
Regular or normal?\n");
for (idxI=0; idxI<size; idxI++) {
printf("\n%15.10lf ", array[idxI]);
9. Megoldsok 79
Heckl Istvn, PE www.tankonyvtar.hu
_flushall();
printf("Decide and press enter to continue!");
scanf("%c", &choice); // just for wait
printf("result: %g\n", array[idxI]);
printf("Was you selection correct? (y)es, (n)o:");
_flushall();
scanf("%c", &choice);
if (choice=='y') {
points++;
}
}
printf("You have %d of %d points.", points, size);
return 0;
}
2.9.2.
#include <stdio.h>
int main() {
int size = 5;
double myArray [] = {3.456, 45697.678, -659.23, -0.0000965,
6.0000001};
int idxI, idxJ, points = 0;
char choice;
char correctChoice;
char buffer [50];
int stringSizeOfAnswer;

printf("How do you think the %%g will display the next numbers?
Regular or normal?\n");
for (idxI = 0; idxI < size; idxI++) {
printf("\n%15.10lf ", myArray[idxI]);
stringSizeOfAnswer = sprintf (buffer, "%g", myArray[idxI]);
printf("Decide, rather %%(e) or %%(f)");
scanf("%c", &choice); // just for wait
getchar(); //for the ENTER
correctChoice = 'f';
for(idxJ=0; idxJ < stringSizeOfAnswer; ++idxJ) {
if(buffer[idxJ] == 'e')
correctChoice = 'e';
}
if (choice == correctChoice) {
printf("Correct!\n");
points++;
}
else
printf("Incorrect!\n");
}
printf("You achieved a(n) %.lf %% result.\n",
(double)points/(double)size*100);
return 0;
}
2.9.3.
#include <stdio.h>
int main() {
int size = 5;
double myArray [] = {3.456, 45697.678, -659.23, -0.0000965,
6.0000001};
int idxI, idxJ, points = 0;
80 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int correct;
char buffer [50];
char tip [50];
int stringSizeOfAnswer;
int precision;

printf("How do you think the %%g will display the next numbers?
Regular or normal?\n");
for (idxI=0; idxI < size; idxI++) {
printf("\n%15.10lf ", myArray[idxI]);
printf("How long should the %%g precision be? ");
scanf("%d", &precision);
stringSizeOfAnswer = sprintf (buffer, "%.*g", precision,
myArray[idxI]);
printf("Your tip: ");
scanf("%s", tip);
correct = 1;
for(idxJ = 0; idxJ < stringSizeOfAnswer; ++idxJ) {
if(buffer[idxJ] == tip[idxJ])
;
else
correct = 0;
}
printf("%s\n", buffer);
if (correct) {
printf("Correct!\n");
points++;
}
else
printf("Incorrect!\n");
}
printf("You achieved a(n) %.lf %% result.\n",
(double)points/(double)size*100);
return 0;
}
2.10.1.
#include <stdio.h>
int main() {
const int size=5;
double row[size], column[size];
int idxI, idxJ;
for (idxI=0; idxI<size; idxI++) {
printf("row[%d]=", idxI);
scanf("%lf", &row[idxI]);
}
for (idxI=0; idxI<size; idxI++) {
printf("column[%d]=", idxI);
scanf("%lf", &column[idxI]);
}
printf("\nHere comes the multiplying table:\n");
printf(" |"); // first row
for (idxI=0; idxI<size; idxI++) {
printf("%12.4lg|", row[idxI]);
}
printf("\n");
for (idxI=0; idxI<(5+1)*(12+1); idxI++) { // 5 is the size, +1 the
first column, 12 width, +1 '|' character
printf("-");
9. Megoldsok 81
Heckl Istvn, PE www.tankonyvtar.hu
}
for (idxI=0; idxI<size; idxI++) {
printf("\n%12.4lg|", column[idxI]); // first column
for (idxJ=0; idxJ<size; idxJ++) {
printf("%12.4lg|", row[idxI]*column[idxJ]);
}
}
return 0;
}
2.10.2.
#include <stdio.h>
#define SIZE 3
#define COLUMN_WIDTH 12
int main() {
short int sum;
short int row[SIZE], column[SIZE];
int idxI, idxJ;

printf("The values must be between -32768 and +32757!\n");
for (idxI = 0; idxI < SIZE; idxI++) {
printf("row[%d]= ", idxI);
scanf("%d", &row[idxI]);
}
for (idxJ = 0; idxJ < SIZE; idxJ++) {
printf("column[%d]=", idxJ);
scanf("%d", &column[idxJ]);
}
printf("\nHere comes the adder table:\n");
printf("%*s|", COLUMN_WIDTH, " ");
for (idxI = 0; idxI < SIZE; idxI++)
printf("%*d|", COLUMN_WIDTH,row[idxI]);
printf("\n");
for (idxI = 0; idxI < (SIZE+1)*(COLUMN_WIDTH+1); idxI++)
printf("-");
for (idxJ = 0; idxJ < SIZE; idxJ++) {
printf("\n%*d|", COLUMN_WIDTH, column[idxJ]);
for (idxI = 0; idxI < SIZE; idxI++) {
sum = row[idxI] + column[idxJ];
if (row[idxI] > 0 && column[idxJ] > 0 && sum < 0)
//tulcsordulas
printf("%*s", COLUMN_WIDTH+1, "x");
else if (row[idxI] < 0 && column[idxJ] < 0 && sum > 0)
//alulcsordulas
printf("%*s", COLUMN_WIDTH+1, "x");
else
printf("%*d", COLUMN_WIDTH+1, sum); //rendes ertek
}
}
printf("\n");
return 0;
}
2.11.1.
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, D, x1, x2;
printf("The next equation is to be solved:\n");
82 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("a*x^2+b*x+c=0\n");
printf("a=");
scanf("%f", &a);
printf("b=");
scanf("%f", &b);
printf("c=");
scanf("%f", &c);
D=b*b-4*a*c;
if (D>0) {
printf("There are 2 solutions!\n");
x1=(-b+sqrt(D))/(2*a);
x2=(-b-sqrt(D))/(2*a);
printf("x1=%f\n", x1);
printf("x2=%f\n", x2);
} else if (D==0) {
printf("There is 1 solution!\n");
x1=-b/(2*a);
printf("x1=%f\n", x1);
} else {
printf("There is no solution!\n");
}
return 0;
}
2.11.2.
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, D, x1, x2; //masodfoku egyenlet megoldokepletenek
parameterei

printf("The next equation is to be solved:\n");
printf("a*x^2+b*x+c=0\n");
printf("a= ");
scanf("%f", &a);
printf("b= ");
scanf("%f", &b);
printf("c= ");
scanf("%f", &c);
D = b*b - 4*a*c;
if (D > 0) {
printf("There are 2 solutions!\n");
x1 = (-b + sqrt(D)) /(2*a);
x2 = (-b - sqrt(D)) /(2*a);
printf("x1= %f\n", x1);
printf("x2= %f\n", x2);
}
else if (D == 0) {
printf("There is 1 solution!\n");
x1 = -b /(2*a);
printf("x1= %f\n", x1);
}
else {
printf("There are 2 solutions! (complex)\n");
printf("x1= %f+(%f)i\n", (-b) /(2*a), sqrt(-D));
printf("x2= %f-(%f)i\n", (-b) /(2*a), sqrt(-D));
}
return 0;
}
9. Megoldsok 83
Heckl Istvn, PE www.tankonyvtar.hu
2.12.1
#include <stdio.h>
#include <math.h>
int main() {
int op1, op2;
char more='y';
while (more=='y') {
printf("\nop1=");
scanf("%d", &op1);
printf("op2=");
scanf("%d", &op2);

printf("%d<%d = %d\n", op1, op2, op1 < op2);
printf("%d<=%d = %d\n", op1, op2, op1 <= op2);
printf("%d==%d = %d\n", op1, op2, op1 == op2);
printf("%d>=%d = %d\n", op1, op2, op1 >= op2);
printf("%d>%d = %d\n", op1, op2, op1 > op2);
printf("%d!=%d = %d\n", op1, op2, op1 != op2);

printf("Do you want to continue? (y, n) ");
_flushall();
scanf("%c", &more);
}
return 0;
}
2.12.2.
#include <stdio.h>
#include <math.h>
int main() {
int op1, op2;
char more = 'y';
while (more == 'y') {
printf("\nop1= ");
scanf("%d", &op1);
printf("op2= ");
scanf("%d", &op2);
printf("%d&%d = %d\n", op1, op2, op1 & op2);
printf("%d|%d = %d\n", op1, op2, op1 | op2);
printf("%d^%d = %d\n", op1, op2, op1 ^ op2);
printf("~%d = %d\n", op1, ~op1);
printf("~%d = %d\n", op2, ~op2);
printf("Do you want to continue? (y, n) ");
_flushall();
scanf("%c", &more);
}
return 0;
}
2.13.1.
#include <stdio.h>
#include <math.h>
int main() {
unsigned char number=0, result, delMask=0x80; // 1000 0000
int idxI;

printf("number=");
scanf("%d", &number);
84 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("Its value in number system 2: ");

for (idxI=0; idxI<8; idxI++) {
result = number & delMask;
printf("%u", result?1:0);
delMask = delMask>>1;
}
printf("\n");
return 0;
}
2.13.2.
#include <stdio.h>
#include <math.h>
#define SIZE 8
int main() {
unsigned char number = 0, result, delMask=0x80; // 1000 0000
unsigned char stringNumber[SIZE], newNumber;
int idxI, position;

printf("Number= ");
scanf("%d", &number);
printf("Its value in system 2: ");
for (idxI = 0; idxI < SIZE; idxI++) {
result = number & delMask;
printf("%u", result?1:0);
stringNumber[idxI] = result?1:0;
delMask = delMask>>1;
}
printf("\nPlease enter a position, this bit will be set to 1!(1 is
the lowest) ");
scanf("%d", &position);
printf("Here comes the new number in system 2: ");
if (!stringNumber[SIZE - position])
newNumber = number + pow(2, position-1);
else
newNumber = number;
stringNumber[SIZE - position] = 1;
for (idxI = 0; idxI < SIZE; idxI++)
printf("%d", stringNumber[idxI]);
printf("\nHere comes the new number in system 10: ");

printf("%d\n", newNumber);
return 0;
}
2.13.3.
#include <stdio.h>
#include <math.h>
#define SIZE 8
int main() {
unsigned char number=0, result, delMask=0x80; // 1000 0000
unsigned char stringNumber[SIZE], newNumber;
int idxI, position, positionDelete, positionNegate;

printf("Number= ");
scanf("%d", &number);
printf("Its value in system 2: ");

9. Megoldsok 85
Heckl Istvn, PE www.tankonyvtar.hu
for (idxI = 0; idxI < SIZE; idxI++) {
result = number & delMask;
printf("%u", result?1:0);
stringNumber[idxI] = result?1:0;
delMask = delMask>>1;
}
printf("\nPlease enter a position, this bit will be set to 1!(1 is
the lowest) ");
scanf("%d", &position);
printf("Here comes the new number in system 2: ");
if (!stringNumber[SIZE - position])
newNumber = number + pow(2, position-1);
else
newNumber = number;
stringNumber[SIZE - position] = 1;
for (idxI = 0; idxI < SIZE; idxI++)
printf("%d", stringNumber[idxI]);
printf("\nHere comes the new number in system 10: ");
printf("%d\n", newNumber);
if (stringNumber[SIZE-position])
newNumber = number + pow(2, position-1);
else
newNumber = number;
printf("%d\n", newNumber);
printf("Please enter 2 new position, the first position bit will be
deleted, the second will be negated.(ex: 1 5) ");
scanf("%d%d", &positionDelete, &positionNegate);
for (idxI = SIZE-positionDelete; idxI < SIZE; ++idxI)
stringNumber[idxI] = stringNumber[idxI+1];
printf("Here comes the new number after bit delete in system 2: ");
for (idxI = 0; idxI < 7; idxI++)
printf("%d", stringNumber[idxI]);
printf("\nHere comes the new number after bit delete in system 10:
");
newNumber = 0;
for (idxI = 6; idxI >= 0; --idxI)
if (stringNumber[idxI] != 0)
newNumber += pow(2, (6-idxI)* stringNumber[idxI]);
printf("%d\n", newNumber);
printf("Here comes the new number after bit delete and bit negate in
system 2: ");
if (stringNumber[SIZE-positionNegate] == 0)
stringNumber[SIZE-positionNegate] = 1;
else
stringNumber[SIZE-positionNegate] = 0;
for (idxI=0; idxI<7; idxI++)
printf("%d", stringNumber[idxI]);
printf("\nHere comes the new number after bit delete and bit negate
in system 10: ");
newNumber = 0;
for (idxI = 6; idxI >= 0; --idxI){
if (stringNumber[idxI] != 0) {
newNumber += pow(2, (6-idxI)* stringNumber[idxI]);
}
}
printf("%d\n", newNumber);
return 0;
}
86 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.14.1.
#include <math.h>
#include <stdio.h>

int main() {
double result, accurateResult, value;
int length, faktor, idxI;
printf("The accuracy of power series calculating e^x\n");
printf("x=" );
scanf("%lf", &value);
printf("lengtgh of the power series=" );
scanf("%d", &length);

accurateResult = exp(value);
result = 1;
faktor = 1;
for (idxI=1; idxI<length; idxI++) {
result += pow(value, idxI)/faktor;
faktor*=(idxI+1);
}
// Sum(i=0..inf, value^i/i!)
printf("The difference between the power series and the exact value
is %lf", accurateResult-result);
// you need longer series to reduce the difference
return 0;
}
2.14.2.
#include <math.h>
#include <stdio.h>
int main() {
double result = 1, accurateResult, value;
int length = 0, faktor = 1, idxI;
double accuracy, difference;

printf("The accuracy of power series calculating e^x\n");
printf("x= " );
scanf("%lf", &value);
printf("How big the accuracy should be? ");
scanf("%lf", &accuracy);
accurateResult = exp(value); //a pontos ertek
difference = accuracy+1; //biztosan elkezdodjon a ciklus
//hatvanysor szamitasa amig le nem csokken a klnbsg a pontossag
ala
for (idxI = 1; difference > accuracy; idxI++) {
result += pow(value, idxI) /faktor;
faktor *= (idxI+1);
difference = accurateResult - result;
length = idxI;
}
printf("A length of %d was necessary to get a difference lower than
%lf\n", length, accuracy);
return 0;
}
2.14.3.
#include <math.h>
#include <stdio.h>
9. Megoldsok 87
Heckl Istvn, PE www.tankonyvtar.hu
int factorial_compute(int);
int main() {
double result = 0, value;
int length, idxI;

printf("The accuracy of sinus series calculating sin(x)\n");
printf("x= " );
scanf("%lf", &value);
printf("length of the sinus series= " );
scanf("%d", &length);
//sin(x) kiszamitasa hatvanysorral
for (idxI=0; idxI < length; idxI++) {
result += (pow(-1, idxI) /factorial_compute(2*idxI + 1)) *
pow(value, 2*idxI + 1);
}
printf("The sin(%lf) value with %d length sinus series is: %lf\n",
value, length, result);
return 0;
}
//egy kulon faktoralis szamito fuggveny, a sin(x) szamitasanak
konnyiteseert
int factorial_compute(int factorial) {
if (factorial == 0)
return 1;
return factorial * factorial_compute(factorial - 1);
}
2.15.1.
#include <math.h>
#include <stdio.h>

int main() {
double doubleValue=1.12345678912346789123456789e5;
printf("%20.20s, doubleValue=");
scanf("%lf", &doubleValue);
float floatValue=(float)doubleValue;
int intValue=(int)floatValue;
short int shortIntValue=(short int)intValue;
char charValue=(char)shortIntValue;

printf("%20.20s%d ", "size of double=", sizeof doubleValue);
printf("doubleValue=%25.20lf\n", doubleValue);
printf("%20.20s%d ", "size of float=", sizeof floatValue);
printf("floatValue=%25.20f\n", floatValue);
printf("%20.20s%d ", "size of int=", sizeof intValue);
printf("intValue=%d\n", intValue);
printf("%20.20s%d ", "size of short int=", sizeof shortIntValue);
printf("shortIntValue=%d\n", shortIntValue);
printf("%20.20s%d ", "size of char=", sizeof charValue);
printf("charValue=%d\n", charValue);
return 0;
}
2.15.2.
#include <stdio.h>

int main() {
double number;

88 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("Mennyi legyen a szam? "); scanf("%lf", &number);
printf("Double-float: %lf\n", number - (float)number);
printf("Double-int: %lf\n", number - (int)number);
printf("Double-short: %.2lf\n", number - (short)number);
printf("Double-char: %.2lf\n", number - (char)number);
return 0;
}
2.16.1.
#include <math.h>
#include <stdio.h>

int main() {
int gotMoney, gotMood, noTime, veryInterested;

printf("Type 1 for yes and 0 for no!\n");
printf("gotMoney=");
scanf("%d", &gotMoney);
printf("gotMood=");
scanf("%d", &gotMood);
printf("noTime=");
scanf("%d", &noTime);
printf("veryInterested=");
scanf("%d", &veryInterested);
if ( (gotMoney && gotMood && !noTime) || (gotMoney && veryInterested)
|| (gotMood && veryInterested) || (!noTime && veryInterested) ) {
printf("I will go to holiday!\n");
} else {
printf("I will not go to holiday!\n");
}
return 0;
}
2.16.2.
#include <stdio.h>
int main() {
int isRaining, comeOthers, gotFreeTime;

printf("Type 1 for yes and 0 for no!\n");
printf("isRaining: ");
scanf("%d", &isRaining);
printf("comeOthers: ");
scanf("%d", &comeOthers);
printf("gotFreeTime: ");
scanf("%d", &gotFreeTime);
if( (!(isRaining || !gotFreeTime)) || (!(!isRaining || comeOthers)) )
printf("I'm going hiking!\n");
else
printf("Peharps next time.\n");
return 0;
}
2.17.1.
#include <stdio.h>

int main() {
float temperature;

printf("temperature of water=");
9. Megoldsok 89
Heckl Istvn, PE www.tankonyvtar.hu
scanf("%f", &temperature);
if (temperature < 0) {
printf("Solid water\n");
} else if (temperature < 100) {
printf("Liquid water\n");
} else {
printf("Gaseous water\n");
}
return 0;
}
2.17.2.
#include <stdio.h>
float changer(float);
int main() {
float celsius;
float fahrenheit;

printf("temperature of water(in fahrenheit): ");
scanf("%f",&fahrenheit);
celsius = changer(fahrenheit);
if (celsius < 0)
printf("The water is solid now.\n");
else if (celsius > 100)
printf("The water is gaseous now.\n");
else
printf("The water is liquid now.\n");
return 0;
}
float changer(float temp) {
return temp = (temp-32) * 5 / 9;
}
2.18.1.
#include <stdio.h>
int main() {
char num;
printf("Roman to arabic number converter");
printf("\nGive me a roman number: ");
scanf("%c", &num);
if (num > 'Z') num = num - ('a'-'A');
switch (num) {
case 'I': printf("\n1"); break;
case 'V': printf("\n5"); break;
case 'X': printf("\n10"); break;
case 'L': printf("\n50"); break;
case 'C': printf("\n100"); break;
case 'D': printf("\n500"); break;
case 'M': printf("\n1000"); break;
default: printf("\nWrong character");
}
return 0;
}
2.18.2.
#include <stdio.h>
#include <ctype.h>
int main() {
char roman[30];
90 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int arabian = 0, size, idxI;

printf("Roman number: ");
scanf("%s", roman);
size = strlen(roman);
for (idxI = 0; idxI < size; idxI++) {
roman[idxI] = toupper(roman[idxI]);
}
for (idxI = 0; idxI < size; idxI++) {
switch (roman[idxI]) {
case 'I':
if (roman[idxI + 1] == 'X') {
arabian += 9;
idxI += 1;
}
else {
if (roman[idxI + 1] == 'V') {
arabian += 4;
idxI += 1;
}
else {
arabian += 1;
}
}
break;
case 'V':
arabian += 5;
break;
case 'X':
if (roman[idxI + 1] == 'C') {
arabian += 90;
idxI += 1;
}
else {
if (roman[idxI + 1] == 'L') {
arabian += 40;
idxI += 1;
}
else {
arabian += 10;
}
}
break;
case 'L':
arabian += 50;
break;
case 'C':

if (roman[idxI + 1] == 'M') {
arabian += 900;
idxI += 1;
}
else {
if (roman[idxI + 1] == 'D') {
arabian += 400;
idxI += 1;
}
else {
arabian += 100;
9. Megoldsok 91
Heckl Istvn, PE www.tankonyvtar.hu
}
}
break;
case 'D':
arabian += 500;
break;
case 'M':
arabian += 1000;
break;
}
}
printf("%d\n", arabian);
return 0;
}
2.18.3.
#include <stdio.h>
int main() {
char roman[20];
int arabian, idxI = 0;
printf("Arabianian number(1-4999): ");
scanf("%d", &arabian);
while (arabian > 0) {
while ((arabian - 1000) >= 0) {
roman[idxI++] = 'M';
arabian -= 1000;
}
while ((arabian - 900) >= 0) {
roman[idxI++] = 'C';
roman[idxI++] = 'M';
arabian -= 900;
}
while ((arabian - 500) >= 0) {
roman[idxI++] = 'D';
arabian -= 500;
}
while ((arabian - 400) >= 0) {
roman[idxI++] = 'C';
roman[idxI++] = 'D';
arabian -= 400;
}
while ((arabian - 100) >= 0) {
roman[idxI++] = 'C';
arabian -= 100;
}
while ((arabian - 90) >= 0) {
roman[idxI++] = 'X';
roman[idxI++] = 'C';
arabian -= 90;
}
while ((arabian - 50) >= 0) {
roman[idxI++] = 'L';
arabian -= 50;
}
while ((arabian - 40) >= 0) {
roman[idxI++] = 'X';
roman[idxI++] = 'L';
arabian -= 40;
}
92 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
while ((arabian - 10) >= 0) {
roman[idxI++] = 'X';
arabian -= 10;
}
while ((arabian - 9) >= 0) {
roman[idxI++] = 'I';
roman[idxI++] = 'X';
arabian -= 9;
}
while ((arabian - 5) >= 0) {
roman[idxI++] = 'V';
arabian -= 5;
}
while ((arabian - 4) >= 0) {
roman[idxI++] = 'I';
roman[idxI++] = 'V';
arabian -= 4;
}
while ((arabian - 1) >= 0) {
roman[idxI++] = 'I';
arabian -= 1;
}
}
roman[idxI++] = '\0';
printf("%s\n", roman);
return 0;
}
2.19.1.
#include <stdio.h>
int main() {
int idxI, idxJ, size=15; // egesz valtozo letrehozasa
for(idxI = 1; idxI <= size; idxI++) {
for(idxJ = 1; idxJ <= idxI; idxJ++) {
printf("*");
}
printf("\n");
}
return 0;
}
2.19.2.
#include <stdio.h>
int main() {
int idxI, idxJ, size = 6;
for (idxI = 0; idxI < size; ++idxI) {
for (idxJ = 1; idxJ <= size; ++idxJ) {
if (idxJ < size -idxI)
printf("");
else
printf("*");
}
printf("\n");
}
return 0;
}
2.20.1.
#include <stdio.h>
9. Megoldsok 93
Heckl Istvn, PE www.tankonyvtar.hu
int main() {
// square falling off, it is supposed that the console is 80*25
character big
// for quick computers set bigger size
int idxA, idxB, idxC, size=600;
int idxI, idxJ, idxK, drop=22, consoleSize=25;

for (idxI=0; idxI<drop; idxI++) {
// erase console
for (idxJ=0; idxJ<consoleSize; idxJ++) {
printf("\n");
}
// position square vertically 1
for (idxK=0; idxK<idxI; idxK++) {
printf("\n");
}
// print square
printf(" ***\n");
printf(" ***\n");
printf(" ***\n");
// position square vertically 2
for (idxK=0; idxK<consoleSize-idxI-3; idxK++) {
printf("\n");
}
_flushall();
// delay
for(idxA = 0; idxA <= size; idxA++) {
for(idxB = 1; idxB <= size; idxB++) {
for(idxC = 1; idxC <= size; idxC++) {
}
}
}
}
return 0;
}
2.20.2.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void wait(int seconds) {
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC;
while (clock() < endwait) {
}
}

int main() {
int idxI, idxJ = 0, size = 0;
while (1) {
system("clear");
size = 4;
if (idxJ == 25)
idxJ = 0;
if (idxJ >= 23) {
for (idxI = idxJ; idxI >= 23; idxI--) {
printf("***\n");
size -= 1;
94 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
}
for (idxI = 1; idxI <= idxJ; idxI++)
printf("\n");
for (idxI = 1; idxI < size; idxI++)
printf("***\n");
wait(1); //ez a mozgas sebessege
idxJ++;
}
return 0;
}
2.20.3.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void wait(int seconds) { //kesleltetes megvalositasa
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC;
while (clock() < endwait) ;
}

int main(){
int idxI, idxJ, row = 0, direction;
while(1) { //vegtelen ciklus
system("clear"); //kepernyo torles
for (idxI = 1; idxI <= row; idxI++) //ures sorok kirajzolasa
printf("\n");
for (idxJ = 0; idxJ < 3; idxJ++) { //szokozok rajzolasa
for (idxI = 2 - idxJ; idxI > 0; idxI--)
printf("");
for (idxI = 0; idxI <= 2*idxJ; idxI++) //csilllagok rajzolasa
printf("*");
printf("\n");
}
//kesz van a haromszog
wait(1); //ez a mozgas sebessege
if (row == 22) //iranyvaltasok
direction = 0;
else if (row == 0)
direction = 1;
if (direction)
row++;
else
row--;
}
return 0;
}
2.20.4.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void wait(int seconds) {
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC;
while (clock() < endwait) ;
9. Megoldsok 95
Heckl Istvn, PE www.tankonyvtar.hu
}

int main() {
int idxI, idxJ = 0, direction;
char string [] = "*****";
while (1) {
system("clear");
for (idxI = 1; idxI < 4; idxI++) //teglalap kirajzolasa, mindig
eggyel elcsusztatva
printf("%*.5s\n", idxJ + 5, string);
wait(1); //ez a mozgas sebessege
if (idxJ == 75) //iranyvaltas
direction = 0;
else if (idxJ == 0)
direction=1;

if (direction)
idxJ++;
else
idxJ--;
}
return 0;
}
2.21.1.
#include <stdio.h>
int main() {
int x, y; // x=30; y=42 ->6
printf("Give me the first number: ");
scanf("%d",&x);
printf("Give me the second number: ");
scanf("%d",&y);
while (x!=y) {
if (x>y)
x=x-y;
else
y=y-x;
}
printf("The biggest common denominator: %d\n", x);
return 0;
}
2.21.2.
#include <stdio.h>
int biggest_denominator(int, int);
int main() {
int x, y, z; //elso, masodik, harmadik szam
int first, second;
printf("Give me the first number: ");
scanf("%d", &x);
printf("Give me the second number: ");
scanf("%d", &y);
printf("Give me the third number: ");
scanf("%d", &z);
//for the first 2 number
first = biggest_denominator(x, y);
//for the second 2 number
second = biggest_denominator(y, z);
96 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("The biggest common denominator: %d\n",
biggest_denominator(first, second)); // compute the result of the fisrt
and second denominations
return 0;
}

int biggest_denominator(int x, int y) {
while (x!=y) {
if (x>y)
x=x-y;
else
y=y-x;
}
return x;
}
2.22.1.
#include <stdio.h>
int main(int argc, char* argv[]) {
int idxI;
for (idxI=argc-1; idxI>=0; idxI--) {
printf("The %d. parameter is: %s\n", idxI, argv[idxI]);
}
return 0;
}
2.22.2.
#include <stdio.h>
int main(int argc, char* argv[]) {
int idxI = argc-1;
do {
printf("The %d. parameter is: %s\n", idxI, argv[idxI]);
idxI--;
} while (idxI>=0);
return 0;
}
2.23.1.
#include <stdio.h>
int main(int argc, char* argv[]) {
int idxI=0;
float x, y;
do {
printf("x=");
scanf("%f", &x);
printf("y=");
scanf("%f", &y);
if ( x>100 || -x>100) {
printf("x is too big!\n");
continue;
}
if (!y) { // y==0
printf("y equals 0!\n");
break;
}
printf("%f/%f=%f\n\n", x, y, x/y);
idxI++;
if (idxI==3)
break;
9. Megoldsok 97
Heckl Istvn, PE www.tankonyvtar.hu
} while (1);
return 0;
}
2.24.1.
#include <stdio.h>

float deriv(int whichDerivate, float where) {
// 3x^3-2x^2+6x-1
float result;

switch (whichDerivate) {
case 1: // 9x^2-4x+6
result = 9*where*where-4*where+6;
break;
case 2: // 18x-4
result = 18*where-4;
break;
case 3: // 18
result = 18;
break;
default:
result = 0;
printf("\nFirst parameter (%d) is wrong, it should be in 1, 2,
or 3\n", whichDerivate);
break;
}
return result;
}
int main() {
int idxI;
float where, rez;

printf("Where do you want to calculate the derivate: ");
scanf("%f", &where);
for (idxI=1; idxI<5; idxI++) {
rez=deriv(idxI, where);
printf("The %d. derivative of 9x^2-4x+6 at %f is: %f\n", idxI,
where, rez);
}
return 0;
}
2.24.2.
#include <stdio.h>
#include <math.h>

float deriv(int whichDerivate, float posX) {
// sin(x)
float result;

switch (whichDerivate%4) {
case 0: // sin(x)
result = sin(posX);
break;
case 1: // cos(x)
result = cos(posX);
break;
case 2: // -sin(x)
98 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
result = -sin(posX);
break;
case 3: // -cos(x)
result = -cos(posX);
break;

default:
result = 0;
printf("\nError!\n");
break;
}
return result;
}
int main() {
int idxI;
float posX, result;
int times;

printf("Where do you want to calculate the derivate of sin(x) (in
radian): ");
scanf("%f", &posX);
printf("How many times? ");
scanf("%d", &times);
for (idxI = 1; idxI <= times; idxI++) {
result = deriv(idxI, posX);
printf("The %d. derivative of sin(x) at %f is: %f\n", idxI, posX,
result);
}
return 0;
}
2.24.3.
#include <stdio.h>
float deriv(float posX, float poly4, float poly3, float poly2, float
poly1, float poly0) {
return ( 4*poly4*pow(posX,3) + 3*poly3*pow(posX,2) +
2*poly2*pow(posX,1) + poly1 );
}
int main() {
float posX, poly4, poly3, poly2, poly1, poly0; //a hely ahol
serivalni szeretnek, s a polinomok egyutthatoi

printf("What function do you want to derivate?\n");
printf("x^4: "); scanf("%f", &poly4);
printf("x^3: "); scanf("%f", &poly3);
printf("x^2: "); scanf("%f", &poly2);
printf("x^1: "); scanf("%f", &poly1);
printf("constant: "); scanf("%f", &poly0);

printf("So, the ");
if (poly4) printf("%f x^4 ", poly4);
if (poly3) printf("%+f x^3 ", poly3);
if (poly2) printf("%+f x^2 ", poly2);
if (poly1) printf("%+f x^1 ", poly1);
if (poly0) printf("%+f ", poly0);
printf("will be derivated.\n");

printf("Where do you want to calculate the derivate: ");
scanf("%f", &posX);
9. Megoldsok 99
Heckl Istvn, PE www.tankonyvtar.hu
printf("The first derivative of the function at %f is: %f\n", posX,
deriv(posX, poly4, poly3, poly2, poly1, poly0));
return 0;
}
2.25.1.
#include <stdio.h>

int sum(int data) {
static int result;
result += data;
return result;
}
int main() {
int num, total;
char more='y';

do {
printf("Provide the next number: ");
scanf("%d", &num);
total = sum(num);
printf("Are there more number: (y/n) ");
_flushall();
scanf("%c", &more);
} while (more=='y');
printf("The The total is %d.\n", total);
return 0;
}
2.25.2.
void cancel() {
int act;
act = sum(0);
sum(-act);
}
2.25.3.
#include <stdio.h>
int sum(int data, int subTotal) {
subTotal += data;
return subTotal;
}
int main() {
int num, total, subTotal=0;
char more = 'y';

do {
printf("Provide the next number: ");
scanf("%d", &num);
subTotal = sum(num, subTotal);
printf("Are there more number: (y/n) ");
_flushall();
scanf("%c", &more);
} while (more == 'y');
total = subTotal;
printf("The total is %d.\n", total);
return 0;
}
100 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.26.1.
#include <stdio.h>

int main() {
int side;
int *side1=&side, *side2=&side, *side3=&side;
int surface, volume;

printf("The side of the cube is: ");
scanf("%d", &side);
surface = 6**side1*(*side2); //* as indirection has big precedence
volume = *side1*(*side2)**side3;
printf("The volume of the cube is: %d\n", volume);
printf("The surface of the cube is: %d\n", surface);
return 0;
}
2.26.2.
printf("The volume of the cube is: %d\n", *&*&volume);
2.26.3.
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>

int main() {
float radius;
float *radius1 = &radius, *radius2 = &radius, *radius3 = &radius;
float surface, volume;

printf("The radius of the ball is: ");
scanf("%f", &radius);
surface = 4 * (*radius1) * (*radius2) * (*radius3) * (M_PI) / 3;
volume = 4 * (*radius1) * (*radius2) * (M_PI);
printf("The volume of the ball is: %f\n", volume);
printf("The surface of the ball is: %f\n", surface);
return 0;
}
2.27.1
#include <stdio.h>

int main() {
int data=42, code=666, temp;
int *realAddress=&data, *changedAddress=0, *tryAddress;

changedAddress = realAddress - code;

printf("The 1st key: %p\n", changedAddress);
printf("Press 1 if the other person arrived: ");
scanf("%d", &temp);
printf("The 2nd key: %d\n", code);
changedAddress = NULL;
code = 0;
printf("To retrieve the data provide the 1st key: ");
scanf("%p", &changedAddress);
printf("Provide the 2nd key: ");
scanf("%d", &code);
tryAddress = changedAddress + code;
9. Megoldsok 101
Heckl Istvn, PE www.tankonyvtar.hu
if (tryAddress==realAddress)
printf("Access granted, the data is: %d\n", *tryAddress);
else
printf("Access denied!\n");
return 0;
}
2.28.1.
#include <stdio.h>

int main() {
int data=42, *pData=&data, **ppData=&pData, ***pppData=&ppData;
int idxI;
printf("%10s %#p %#p %#p %#p \n", "address: ",
&pppData, &ppData, &pData, &data);
printf("%10s ", "");
for (idxI=0; idxI<4; idxI++)
printf("------------ ");
printf("\n%10s |%#p| |%#p| |%#p| |%10d| \n", "value:",
pppData, ppData, pData, data);
printf("%10s ", "");
for (idxI=0; idxI<4; idxI++)
printf("------------ ");
printf("\n%10s %-15s%-15s%-15s%-15s", "variable:", "pppData",
"ppData", "pData", "data");
printf("\n%10s %-15s%-15s%-15s%-15s", "", "", "*pppData", "*ppData",
"*pData");
printf("\n%10s %-15s%-15s%-15s%-15s", "", "", "", "**pppData",
"**ppData");
printf("\n%10s %-15s%-15s%-15s%-15s", "", "", "", "", "***pppData");
return 0;
}
2.28.2
#include <stdio.h>

int main() {
double** myMatrix;
int *pData=&myMatrix, **ppData=&pData, ***pppData=&ppData;
int idxI, idxJ, idxK, temp = 0;

//dinamikus memriafoglals
myMatrix = (double**)malloc(2 * sizeof(double*));
for (idxI=0; idxI<2; idxI++) {
myMatrix[idxI] = (double*)malloc(3 * sizeof(double));
}
for(idxI = 0; idxI < 2; idxI++)
for(idxJ = 0; idxJ < 3; idxJ++)
myMatrix[idxI][idxJ] = ++temp;
printf("****Adresses****\n");
printf("myMatrix**: [%#p] -> myMatrix[0,1]*: [%#p, %#p]\n",
&myMatrix, &myMatrix[0], &myMatrix[1]);
printf("myMatrix[0]*: [%#p]-> myMatrix[0][0,1,2]: [%#p, %#p, %#p]\n",
&myMatrix[0], &myMatrix[0][0], &myMatrix[0][1], &myMatrix[0][2]);
printf("myMatrix[1]*: [%#p]-> myMatrix[1][0,1,2]: [%#p, %#p, %#p]\n",
&myMatrix[1], &myMatrix[1][0], &myMatrix[1][1], &myMatrix[1][2]);
printf("\n***Values****\n");
printf("myMatrix**: [%#p] : myMatrix[0,1]*: [%#p, %#p]\n", myMatrix,
myMatrix[0], myMatrix[1]);
102 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("myMatrix[0]*: [%#p] : myMatrix[0][0,1,2]: [%.2lf, %.2lf,
%.2lf]\n", myMatrix[0], myMatrix[0][0], myMatrix[0][1], myMatrix[0][2]);
printf("myMatrix[1]*: [%#p] : myMatrix[1][0,1,2]: [%.2lf, %.2lf,
%.2lf]\n", myMatrix[1], myMatrix[1][0], myMatrix[1][1], myMatrix[1][2]);

for (idxI=0; idxI<2; idxI++) //felszabadits
free(myMatrix[idxI]);
free(myMatrix);
return 0;
}
2.29.1.
#include <stdio.h>
#include <malloc.h>

int main() {
int choice;
short int *si1=NULL, *si2=NULL;
long double *ld1=NULL, *ld2=NULL;
printf("Short int operands (1)\n");
printf("Long double operands (2)\n");
scanf("%d", &choice);
switch (choice) {
case 1:
si1 = (short int*)malloc(1*sizeof(short int));
si2 = (short int*)malloc(1*sizeof(short int));
printf("si1=");
scanf("%hd", si1);
printf("si2=");
scanf("%hd", si2);
*si1 = *si1 + * si2;
printf("The increased value is: %hd\n", *si1);
free(si1); si1=NULL;
free(si2); si2=NULL;
break;
case 2:
ld1 = (long double*)malloc(1*sizeof(long double));
ld2 = (long double*)malloc(1*sizeof(long double));
printf("ld1=");
scanf("%Lf", ld1);
printf("ld2=");
scanf("%Lf", ld2);
*ld1 = *ld1 + *ld2;
printf("The increased value is: %Lf\n", *ld1);
free(ld1); ld1=NULL;
free(ld2); ld2=NULL;
break;
}
return 0;
}
2.30.1.
#include <stdio.h>
struct Var {
char varChar;
short int varShortInt;
int varInt;
float varFloat;
double varDouble;
9. Megoldsok 103
Heckl Istvn, PE www.tankonyvtar.hu
long double varLongDouble;
int *varPInt;
};

int main() {
struct Var myVar;
printf("varChar=");
scanf("%c", &myVar.varChar);
printf("varShortInt=");
scanf("%hd", &myVar.varShortInt);
printf("varInt=");
scanf("%d", &myVar.varInt);
printf("varFloat=");
scanf("%f", &myVar.varFloat);
printf("varDouble=");
scanf("%lf", &myVar.varDouble);
printf("varLongDouble=");
scanf("%Lf", &myVar.varLongDouble);
printf("varPInt=");
scanf("%p", &myVar.varPInt);

printf("\nmyVar\n");
printf("varChar=%c\n", myVar.varChar);
printf("varShortInt=%hd\n", myVar.varShortInt);
printf("varInt=%d\n", myVar.varInt);
printf("varFloat=%g\n", myVar.varFloat);
printf("varDouble=%lg\n", myVar.varDouble);
printf("varLongDouble=%Lg\n", myVar.varLongDouble);
printf("varPInt=%p", myVar.varPInt);
return 0;
}
2.30.2.
#include <stdio.h>
#include <malloc.h>

struct Var {
char varChar;
short int varShortInt;
int varInt;
float varFloat;
double varDouble;
long double varLongDouble;
int *varPInt;
};
typedef struct Var VarType;

void readVarType(VarType *myVar) {
printf("varChar=");
scanf("%c", &myVar->varChar);
printf("varShortInt=");
scanf("%hd", &myVar->varShortInt);
printf("varInt=");
scanf("%d", &myVar->varInt);
printf("varFloat=");
scanf("%f", &myVar->varFloat);
printf("varDouble=");
scanf("%lf", &myVar->varDouble);
printf("varLongDouble=");
104 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
scanf("%Lf", &myVar->varLongDouble);
myVar->varPInt = &myVar->varInt;
}

void printVarType(VarType myVar) {
printf("\nmyVar\n");
printf("varChar=%c\n", myVar.varChar);
printf("varShortInt=%hd\n", myVar.varShortInt);
printf("varInt=%d\n", myVar.varInt);
printf("varFloat=%g\n", myVar.varFloat);
printf("varDouble=%lg\n", myVar.varDouble);
printf("varLongDouble=%Lg\n", myVar.varLongDouble);
printf("*varPInt=%d", *myVar.varPInt);
}

int main() {
VarType myVar, *copy=NULL;
readVarType(&myVar);
printVarType(myVar);
copy = (VarType*)malloc(sizeof(VarType)*1);
*copy = myVar;
printVarType(*copy);
*((*copy).varPInt)=666; // *(*copy).varPInt=666; *copy->varPInt=666;
printVarType(myVar);
free(copy); copy=NULL;
return 0;
}
2.31.1.
#include <stdio.h>
#include <malloc.h>
typedef struct {
char name[200];
int age;
int ID;
} Person;

typedef struct {
int carat;
float price;
int numberOfStones;
} Ring;

typedef struct {
Person man, wife;
Ring weddingRing, engagementRing;
int guestNumber;
Person *guests;
} Wedding;

void printPerson(Person myPerson) {
printf("person{");
printf("name=%s, ", myPerson.name);
printf("age=%d, ", myPerson.age);
printf("ID=%d}", myPerson.ID);
}

void printRing(Ring myRing) {
printf("ring{");
9. Megoldsok 105
Heckl Istvn, PE www.tankonyvtar.hu
printf("carat=%d, ", myRing.carat);
printf("price=%f, ", myRing.price);
printf("number of stones=%d}", myRing.numberOfStones);
}

void printWedding(Wedding myWedding) {
int idxI;
printf("wedding{\n\tman=");
printPerson(myWedding.man);
printf(",\n\twife=");
printPerson(myWedding.wife);
printf(",\n\twedding ring=");
printRing(myWedding.weddingRing);
printf(",\n\tengagement ring=");
printRing(myWedding.engagementRing);
printf(",\n\tGuests={");
for (idxI=0; idxI<myWedding.guestNumber; idxI++) {
printf("\n\t\t");
printPerson(myWedding.guests[idxI]);
printf(",");
}
printf("\n\t}\n}");
}

int main() {
const int friendNumber=3;
Person friends[friendNumber]={{"Jani", 28, 12345}, {"Emese", 29,
66666}, {"Zoli", 32, 222222}};
Wedding brotherWedding={
{"Arpi", 32, 23332},
{"Panna", 29, 22222},
{16, 60000, 0},
{24, 200000, 3},
friendNumber, friends
};
printf("brotherWedding=");
printWedding(brotherWedding);
return 0;
}
2.32.1.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef struct {
char manufacturer[20]; // static
int productNumber;
char* description; // dynamic
float price;
} Fan;
Fan readFan() {
Fan rec;
int descriptionLength;
printf("Provide the data of the fan!\n");
printf("manufacturer: ");
gets(rec.manufacturer);
printf("product number: ");
scanf("%d", &rec.productNumber);
printf("max description length: ");
106 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
scanf("%d", &descriptionLength);
rec.description = (char*)malloc(sizeof(char)*descriptionLength);
_flushall();
printf("description: ");
gets(rec.description);
printf("price:");
scanf("%f", &rec.price);
//. preferenija nagyobb a mint az &-e
return rec;
}
void printFan(Fan rec) {
printf("Fan data\n");
printf("manufacturer: %s\n", rec.manufacturer);
printf("product number:%d\n", rec.productNumber);
printf("description:%s\n", rec.description);
printf("price:%5.2f HUF\n", rec.price);
}
int main() {
Fan myFan;
myFan = readFan();
printFan(myFan);
free(myFan.description); myFan.description=NULL;
return 0;
}
2.32.2.
#include <stdio.h>
#include <string.h>
#include <malloc.h>

typedef struct {
char manufacturer[20]; // static
int productNumber;
char* description; // dynamic
float price;
} Fan;

Fan readFan() {
Fan rec;
int descriptionLength;

printf("Provide the data of the fan!\n");
printf("manufacturer: ");
scanf("%s", rec.manufacturer);
printf("product number: ");
scanf("%d", &rec.productNumber);
printf("max description length: ");
scanf("%d", &descriptionLength);
rec.description = (char*) malloc(sizeof(char) * descriptionLength);
printf("description: ");
scanf("%s", rec.description);
printf("price: ");
scanf("%f", &rec.price);
//. preferenija nagyobb a mint az &-e
return rec;
}

void printFan(Fan rec) {
printf("manufacturer: %s\n", rec.manufacturer);
9. Megoldsok 107
Heckl Istvn, PE www.tankonyvtar.hu
printf("product number:%d\n", rec.productNumber);
printf("description:%s\n", rec.description);
printf("price:%5.2f HUF\n", rec.price);
}

int main() {
Fan myFan,myFan2;
myFan = readFan();
myFan2=myFan;
myFan.description="A new file";
printf("Fan data\n");
printFan(myFan);
printf("Fan2 data\n");
printFan(myFan2);
free(myFan.description);
myFan.description = NULL;
free(myFan2.description);
myFan2.description = NULL;

return 0;
}
2.33.1.
#include <stdio.h>

const int maxStudentNumber=100;
const int maxCodeLength=6;

typedef struct {
int sNum;
char sCode[maxStudentNumber][maxCodeLength+1];
float sPoints[maxStudentNumber];
} Class;

void printClass(Class *myClass, char comments[4][3][40]) {
int idxI;
printf("%+10s%#20p%#20p%#20p\n", "address: ", myClass, myClass-
>sCode, myClass->sPoints);
printf("%+10s%20d%20c%20.1f\n", "value: ", myClass->sNum, myClass-
>sCode[0][0], myClass->sPoints[0]);
for (idxI=0; idxI<4; idxI++) {
printf("%10s%20s%20s%20s\n", "", comments[idxI][0],
comments[idxI][1], comments[idxI][2]);
}
}

int main() {
Class myCl[2]={
{3, {"AA34", "BE3E", "CLY56"}, {16.4, 23.2, 40.0}},
{2, {"NMA444", "SE63"}, {13.2, 50.0}},
};
char myComments[4][3][40]= {
{"myCl[0] "},
{"myCl[0].sNum", "myCl[0].sCode", "myCl[0].sPoints"},
{"", "myCl[0].sCode[0]",
"myCl[0].sPoints[0]"},
{"", "myCl[0].sCode[0][0]"}
};

108 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printClass(&myCl[0], myComments);
printf("\n\n");
myComments[0][0][5] = '1';
myComments[1][0][5] = '1';
myComments[1][1][5] = '1';
myComments[1][2][5] = '1';
myComments[2][1][5] = '1';
myComments[2][2][5] = '1';
myComments[3][1][5] = '1';
printClass(&myCl[1], myComments);
return 0;
}
2.34.1.
#include <stdio.h>
const int maxStudentNumber=100;
const int maxCodeLength=6;

typedef struct {
char name[100];
unsigned int sex :1; // 0 - female, 1 - male
unsigned int grownUp :1; // 0 - no, 1 - yes
unsigned int zodiac :6; // 0 - Aries, 1 - Taurus, 2 - Gemini, 3 -
Cancer, 4 - Leo
// 5 - Virgo, 6- Libra, 7 - Scorpio, 8 - Sagittarius, 9 - Capricorn,
10 - Aquarious
// 11 - Pisces
unsigned int religion :3; // 0 - Judaism, 1 - Christian, 2 - Islam, 3
- Hinduism, 4 - Budhism, 5 - other
unsigned int bloodType :2; // 0 - 0, 1 - A, 2 - B, 3 - AB
unsigned int RH :1; // 0 - -, 1 - +
} Person;

void readPerson(Person *myPerson) {
int dummy;
printf("name=");
scanf("%s", myPerson->name);

printf("sex: 0 - female, 1 - male ");
scanf("%d", &dummy);
myPerson->sex=dummy;

printf("grown up: 0 - no, 1 - yes ");
scanf("%d", &dummy);
myPerson->grownUp=dummy;

printf("zodiac: 0 - Aries, 1 - Taurus, 2 - Gemini, 3 - Cancer, 4 -
Leo, 5 - Virgo, \
6 - Libra, 7 - Scorpio, 8 - Sagittarius, 9 - Capricorn, 10 -
Aquarious, 11 - Pisces ");
scanf("%d", &dummy);
myPerson->zodiac=dummy;

printf("religion: 0 - Judaism, 1 - Christian, 2 - Islam, 3 -
Hinduism, \
4 - Budhism, 5 - other ");
scanf("%d", &dummy);
myPerson->religion=dummy;

9. Megoldsok 109
Heckl Istvn, PE www.tankonyvtar.hu
printf("bloodType: 0 - 0, 1 - A, 2 - B, 3 - AB ");
scanf("%d", &dummy);
myPerson->bloodType=dummy;

printf("RH: 0 - -, 1 - + ");
scanf("%d", &dummy);
myPerson->RH=dummy;
}

void printPerson(Person *myPerson) {
printf("person={name=%s, sex=", myPerson->name);
switch (myPerson->sex) {
case 0: printf("female, "); break;
case 1: printf("male, "); break;
}
printf("grown up=");
switch (myPerson->grownUp) {
case 0: printf("no, "); break;
case 1: printf("yes, "); break;
}
printf("zodiac=");
switch (myPerson->zodiac) {
case 0: printf("Aries, "); break;
case 1: printf("Taurus, "); break;
case 2: printf("Gemini, "); break;
case 3: printf("Cancer, "); break;
case 4: printf("Leo, "); break;
case 5: printf("Virgo, "); break;
case 6: printf("Libra, "); break;
case 7: printf("Scorpio, "); break;
case 8: printf("Sagittarius, "); break;
case 9: printf("Capricorn, "); break;
case 10: printf("Aquarious, "); break;
case 11: printf("Pisces, "); break;
}
printf("religion=");
switch (myPerson->religion) {
case 0: printf("Judaism, "); break;
case 1: printf("Christian, "); break;
case 2: printf("Islam, "); break;
case 3: printf("Hinduism, "); break;
case 4: printf("Budhism, "); break;
case 5: printf("other, "); break;
}
printf("bloodType=");
switch (myPerson->bloodType) {
case 0: printf("0, "); break;
case 1: printf("A, "); break;
case 2: printf("B, "); break;
case 3: printf("AB, "); break;
}
printf("RH=");
switch (myPerson->RH) {
case 0: printf("-} "); break;
case 1: printf("+} "); break;
}
printf("structure size in bytes = %d\n", sizeof(*myPerson));
}

110 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int main() {
Person me;
readPerson(&me);
printf("\n");
printPerson(&me);
return 0;
}
2.34.2.
#include <stdio.h>
const int maxStudentNumber = 100;
const int maxCodeLength = 6;

typedef struct {
char name[100];
unsigned int sex; // 0 - female, 1 - male
unsigned int grownUp; // 0 - no, 1 - yes
unsigned int zodiac; // 0 - Aries, 1 - Taurus, 2 - Gemini, 3 -
Cancer, 4 - Leo
// 5 - Virgo, 6- Libra, 7 - Scorpio, 8 - Sagittarius, 9 - Capricorn,
10 - Aquarious
// 11 - Pisces
unsigned int religion; // 0 - Judaism, 1 - Christian, 2 - Islam, 3 -
Hinduism, 4 - Budhism, 5 - other
unsigned int bloodType; // 0 - 0, 1 - A, 2 - B, 3 - AB
unsigned int RH; // 0 - -, 1 - +
} Person;

void readPerson(Person *myPerson) {
int dummy;
printf("name=");
scanf("%s", myPerson->name);

printf("sex: 0 - female, 1 - male ");
scanf("%d", &dummy);
myPerson->sex = dummy;

printf("grown up: 0 - no, 1 - yes ");
scanf("%d", &dummy);
myPerson->grownUp = dummy;

printf(
"zodiac: 0 - Aries, 1 - Taurus, 2 - Gemini, 3 - Cancer, 4 -
Leo, 5 - Virgo, \
6 - Libra, 7 - Scorpio, 8 - Sagittarius, 9 - Capricorn, 10 -
Aquarious, 11 - Pisces ");
scanf("%d", &dummy);
myPerson->zodiac = dummy;

printf(
"religion: 0 - Judaism, 1 - Christian, 2 - Islam, 3 -
Hinduism, \
4 - Budhism, 5 - other ");
scanf("%d", &dummy);
myPerson->religion = dummy;

printf("bloodType: 0 - 0, 1 - A, 2 - B, 3 - AB ");
scanf("%d", &dummy);
myPerson->bloodType = dummy;
9. Megoldsok 111
Heckl Istvn, PE www.tankonyvtar.hu

printf("RH: 0 - -, 1 - + ");
scanf("%d", &dummy);
myPerson->RH = dummy;
}

void printPerson(Person *myPerson) {
printf("person={name=%s, sex=", myPerson->name);
switch (myPerson->sex) {
case 0:
printf("female, ");
break;
case 1:
printf("male, ");
break;
}
printf("grown up=");
switch (myPerson->grownUp) {
case 0:
printf("no, ");
break;
case 1:
printf("yes, ");
break;
}
printf("zodiac=");
switch (myPerson->zodiac) {
case 0:
printf("Aries, ");
break;
case 1:
printf("Taurus, ");
break;
case 2:
printf("Gemini, ");
break;
case 3:
printf("Cancer, ");
break;
case 4:
printf("Leo, ");
break;
case 5:
printf("Virgo, ");
break;
case 6:
printf("Libra, ");
break;
case 7:
printf("Scorpio, ");
break;
case 8:
printf("Sagittarius, ");
break;
case 9:
printf("Capricorn, ");
break;
case 10:
printf("Aquarious, ");
112 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
break;
case 11:
printf("Pisces, ");
break;
}
printf("religion=");
switch (myPerson->religion) {
case 0:
printf("Judaism, ");
break;
case 1:
printf("Christian, ");
break;
case 2:
printf("Islam, ");
break;
case 3:
printf("Hinduism, ");
break;
case 4:
printf("Budhism, ");
break;
case 5:
printf("other, ");
break;
}
printf("bloodType=");
switch (myPerson->bloodType) {
case 0:
printf("0, ");
break;
case 1:
printf("A, ");
break;
case 2:
printf("B, ");
break;
case 3:
printf("AB, ");
break;
}
printf("RH=");
switch (myPerson->RH) {
case 0:
printf("-}");
break;
case 1:
printf("+}");
break;
}
printf("structure size in bytes = %d\n", sizeof(*myPerson));
}
int main() {
Person me;
readPerson(&me);
printf("\n");
printPerson(&me);
return 0;
}
9. Megoldsok 113
Heckl Istvn, PE www.tankonyvtar.hu
2.35.1.
#include <stdio.h>

typedef enum {
awfull, bad, weak, good, excelent
} Result;

void printResult(Result value) {
switch (value) {
case awfull: printf("awfull"); break;
case bad: printf("bad"); break;
case weak: printf("weak"); break;
case good: printf("good"); break;
case excelent: printf("excelent"); break;

}
}

int main() {
Result exam1, exam2;
int dummy;

printf("Provide the result of your exam:\nawfull - %d, bad - %d, weak
- %d, good- %d, excelent - %d ", awfull, bad, weak, good, excelent);
scanf("%d", &dummy);
exam1 = (Result)dummy;
printf("\nYour result is: ");
printResult(exam1);
printf("\n\nProvide the result of your repeating exam:\nawfull - %d,
bad - %d, weak - %d, good- %d, excelent - %d ", awfull, bad, weak, good,
excelent);
scanf("%d", &dummy);
exam2 = (Result)dummy;

if (exam1 < exam2) {
printf("Very good, you improved!");
}
if (exam1 == exam2) {
printf("At least you tried!");
}
if (exam1 > exam2) {
printf("You must be very unlucky!");
}
return 0;
}
2.35.2.
define hasznlata esetn, amikor bevezetjk a kzepes rtkelst, akkor kt rossz lehetsg
kzl vlaszthatunk. Vagy eltoljuk a kzepes feletti eredmnyeket, hogy helyet csinljunk a
kzepesnek vagy olyan egsz rtket rendelnk a kzepeshez, amely nagyobb, mint a kivlhoz
tartoz rtk.
2.36.1.
#include <stdio.h>
#include <io.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
114 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

int main() {
char buffer[50];
char dosCommand[200] = "echo /* End of file */ >> ";

printf("file name=");
scanf("%s", buffer);
if( _chmod(buffer, _S_IREAD | _S_IREAD) == -1 )
printf("File not found\n");
else
printf("Mode changed to read-only\n");
strcat(dosCommand, buffer);
system(dosCommand);

/* Change back to read/write: */
if( _chmod(buffer, _S_IWRITE ) == -1)
printf("File not found\n");
else
printf("Mode changed to read/write\n");
system(dosCommand);
return 0;
}
2.36.2.
#include <stdio.h>
#include <io.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>

int main() {
char buffer[50];
char dosCommand[200] = "echo /* End of file */ >> ";

printf("file name=");
scanf("%s", buffer);
strcat(dosCommand, buffer);

/* Change to read/write: */
if (_chmod(buffer, _S_IWRITE) == -1)
printf("File not found\n");
else {
printf("Mode changed to read/write\n");
remove(buffer);
printf("File deleted\n");
}
return 0;
}
2.37.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
extern int errno;

int main(int argc, char* argv[]) {
char oldName[50], newName[50];
int result;
9. Megoldsok 115
Heckl Istvn, PE www.tankonyvtar.hu
if (argc != 3) {
printf("Usage:\n prgName oldName newName\n");
exit(1);
}
strcpy(oldName, argv[1]);
strcpy(newName, argv[2]);
rename(oldName, newName);
result = errno;
switch (result) {
case 0:
printf("Done! ");
break;
case EEXIST:
printf("%s already exists!", newName);
break;
case ENOENT:
printf("%s does not exist!", oldName);
break;
case EINVAL:
printf("Wrong characters in '%s'!", newName);
break;

}
return 0;
}
2.38.1.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
FILE* tf;
int idxI, data, min, max;
char fileName[200];
double num;

printf("This program will save certain ammount number random number
in a file.\n");
printf("file name=");
scanf("%s", fileName);
printf("min number=");
scanf("%d", &min);
printf("max number=");
scanf("%d", &max);
printf("number of data=");
scanf("%lf", &num);

srand((unsigned)time(NULL));
tf=fopen(fileName, "w");
if (tf==NULL) {
fprintf(stderr, "File open to write has failed!\n");
exit(-1);
}
for(idxI=0; idxI<(int)num; idxI++) {
data = rand()+max+1-min;
fprintf(tf, "%d\n", data);
}
fclose(tf); tf = NULL;
return 0;
116 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
2.38.2.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main() {
FILE* tf;
int idxI, data, min, max, db = 0;
char fileName[200];
int num;

printf("This program will save certain ammount number random number
in a file.\n");
printf("file name=");
scanf("%s", fileName);
printf("min number=");
scanf("%d", &min);
printf("max number=");
scanf("%d", &max);
printf("number of data=");
scanf("%d", &num);
srand((unsigned) time(NULL));
tf = fopen(fileName, "w");
if (tf == NULL) {
fprintf(stderr, "File open to write has failed!\n");
exit(-1);
}
fprintf(tf, "%d\n", num);
for (idxI = 0; idxI < num; idxI++) {
data = rand() % (max + 1 - min) + min;
fprintf(tf, %d\t, data);
db++;
if (db == 100) {
fprintf(tf, "\n");
db = 0;
}
}
fclose(tf);
tf = NULL;
return 0;
}
2.39.1.
#include <stdio.h>
#include <stdlib.h>

double average(char* fileName) {
double result, sum=0;
int counter=0, data;
FILE* file;

file = fopen(fileName, "r");
while ( !feof(file) ) {
fscanf(file, "%d", &data);
counter++;
sum += data;
}
9. Megoldsok 117
Heckl Istvn, PE www.tankonyvtar.hu
fclose(file); file = NULL;
result = sum / counter;
return result;
}

int main() {
FILE *orig=NULL, *even=NULL, *odd=NULL;
int evenCounter=0, oddCounter=0, data;
char origFileName[200], evenFileName[200]="even.txt",
oddFileName[200]="odd.txt";
double evenAverage, oddAverage;

printf("This program will divide a bunch of number according to
parity.\n");
printf("file name=");
scanf("%s", origFileName);
orig = fopen(origFileName, "r");
if (orig == NULL) {
fprintf(stderr, "File open to read has failed!\n");
exit(-1);
}
even = fopen(evenFileName, "w");
odd = fopen(oddFileName, "w");

while ( !feof(orig) ) {
fscanf(orig, "%d", &data);
if (data%2 == 0) {
evenCounter++;
fprintf(even, "%d\n", data);
} else {
oddCounter++;
fprintf(odd, "%d\n", data);
}
}
fclose(orig); orig = NULL;
fclose(even); even = NULL;
fclose(odd); odd = NULL;
printf("There were %d even and %d odd number, their ratio is:
%8lg\n", evenCounter, oddCounter, (double)evenCounter/oddCounter);
evenAverage = average(evenFileName);
oddAverage = average(oddFileName);
printf("The average of the even numbers: %.9lg\nThe average of the
odd numbers: %.9lg\n", evenAverage, oddAverage);
return 0;
}
2.40.1.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int ID;
double price;
} Car;

typedef struct {
char name[200];
int age;
int carNumber;
118 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Car* myCars;
} Person;

void printHalfTag(FILE* file, int depth, char* tag) {
int idxI;
for (idxI=0; idxI<depth; idxI++) {
fprintf(file, "\t");
}
fprintf(file, "<%s>\n", tag);
}

void printFullTag(FILE* file, int depth, char* tag, char* text) {
int idxI;
for (idxI=0; idxI<depth; idxI++) {
fprintf(file, "\t");
}
fprintf(file, "<%s>%s</%s>\n", tag, text, tag);
}

void printPerson(FILE* file, Person* buddy) {
int idxI;
char temp[500];
printHalfTag(file, 0, "Person");
printFullTag(file, 1, "Name", buddy->name);
sprintf(temp, "%d", buddy->age);
printFullTag(file, 1, "Age", temp);
printFullTag(file, 1, "Count", buddy-> carNumber);
for (idxI=0; idxI<buddy->carNumber; idxI++) {
printHalfTag(file, 1, "Car");
sprintf(temp, "%d", buddy->myCars[idxI].ID);
printFullTag(file, 2, "ID", temp);
sprintf(temp, "%lf", buddy->myCars[idxI].price);
printFullTag(file, 2, "price", temp);
printHalfTag(file, 1, "/Car");
}
printHalfTag(file, 0, "/Person");
}

int main() {
const int buddyNumber=3;
int idxI;
Car init[buddyNumber][3]={ { {0, 50}, {2, 12.369}, {21, 0.569} },
{{6, 21}, {1, 15.4}},
{{3, 5.7}}, };
Person buddies[buddyNumber]={{"Jani", 22, 3, init[0]}, {"Evi", 36, 2,
init[1]}, {"Zotya", 25, 1, init[2]} };
FILE *file=NULL;
char fileName[200]="car.txt";

file = fopen(fileName, "w");

for (idxI=0; idxI<buddyNumber; idxI++) {
printPerson(file, &buddies[idxI]);
}
fclose(file); file = NULL;
return 0;
}
9. Megoldsok 119
Heckl Istvn, PE www.tankonyvtar.hu
2.40.2.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int ID;
double price;
} Car;

typedef struct {
char name[200];
int age;
int carNumber;
Car* myCars;
} Person;

void printHalfTag(FILE* file, int depth, char* tag) {
int idxI;

for (idxI = 0; idxI < depth; idxI++) {
fprintf(file, "\t");
}
fprintf(file, "<%s>\n", tag);
}

void printFullTag(FILE* file, int depth, char* tag, char* text) {
int idxI;

for (idxI = 0; idxI < depth; idxI++) {
fprintf(file, "\t");
}
fprintf(file, "<%s\"%s\"/>\n", tag, text);
}

void printPerson(FILE* file, Person* buddy) {
int idxI;
char temp[500];

printHalfTag(file, 0, "Person");
printFullTag(file, 1, "Name value=", buddy->name);
sprintf(temp, "%d", buddy->age);
printFullTag(file, 1, "Age value=", temp);
printHalfTag(file, 1, "Cars");
for (idxI = 0; idxI < buddy->carNumber; idxI++) {
printHalfTag(file, 2, "Car");
sprintf(temp, "%d", buddy->myCars[idxI].ID);
printFullTag(file, 3, "Id value", temp);
sprintf(temp, "%lf", buddy->myCars[idxI].price);
printFullTag(file, 3, "Price value=", temp);
printHalfTag(file, 2, "/Car");
}
printHalfTag(file, 1, "/Cars");
printHalfTag(file, 0, "/Person");
}

int main() {
const int buddyNumber = 3;
int idxI;
120 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Car init[3][3] = { { { 0, 50 }, { 2, 12.369 }, { 21, 0.569 } }, {
{ 6, 21 }, { 1, 15.4 }
}, { { 3, 5.7 } },
};
Person buddies[3] = { { "Jani", 22, 3, init[0] },
{ "Evi", 36, 2, init[1] }, { "Zotya", 25, 1, init[2] }
};
FILE *file = NULL;
char fileName[200] = "car.txt";

file = fopen(fileName, "w");
for (idxI = 0; idxI < buddyNumber; idxI++) {
printPerson(file, &buddies[idxI]);
}
fclose(file);
file = NULL;
printf("XML file created in car.txt.\n");
return 0;
}
2.40.3.
// file.xml begins
<Person>
<Name>Jani</Name>
<Age>22</Age>
<Car>
<ID>0</ID>
<price>50.000000</price>
</Car>
<Car>
<ID>2</ID>
<price>12.369000<price>
</Car>
<Car>
<ID>21</ID>
<price>0.569000</price>
</Car>
</Person>
<Person>
<Name>Evi</Name>
<Age>36</Age>
<Car>
<ID>6</ID>
<price>21.000000</price>
</Car>
<Car>
<ID>1<ID>
<price>15.400000</price>
</Car>
</Person>
<Person>
<Name>Zotya</Name>
<Age>25</Age>
<Car>
<ID>3</ID>
<price>5.700000</price>
</Car>
</Person>
// file.xml ends
9. Megoldsok 121
Heckl Istvn, PE www.tankonyvtar.hu


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
char data[200][200];
char tag[50], newtag[50];
int idxI, idxJ, idxK, rows = 0, TagIdx = 0, Found = 0,Error=0;
FILE * fd = fopen("file.xml", "r");
if (!fd) {
printf("file.xml is not found");
exit(1);
}
while (!feof(fd)) {
fscanf(fd, "%s", data[rows]);
rows++;
}
for (idxI = 0; idxI < rows; idxI++) {
idxJ = 0;
TagIdx = 0;
Found = 0;
if (data[idxI][idxJ] == '<' && data[idxI][idxJ + 1] != '/') {
do {
tag[TagIdx] = data[idxI][idxJ];
TagIdx++;
idxJ++;
} while (data[idxI][TagIdx - 1] != '>');
tag[TagIdx] = '\0';
newtag[strlen(tag) + 1] = '\0';
for (idxK = strlen(tag); idxK > 0; idxK--) {
if (idxK != 1) {
newtag[idxK] = tag[idxK - 1];
} else
newtag[idxK] = '/';
}
newtag[0] = tag[0];
if (strlen(data[idxI]) > strlen(tag)) {
if (strstr(data[idxI], newtag)) {
Found = 1;
data[idxK][0] = '\0';
} else {
printf("Error at line: %d.\n\tNo close TAG for %s.\n",
idxI + 1,
tag);
Error=1;
}
} else {
for (idxK = idxI+1; idxK < rows; idxK++) {
if (!strcmp(tag, data[idxK]) && !Found) {
printf("At line %d.\n\tNo closeTAG for %s.\n",
idxI+1,tag);
Error=1;
idxK=rows;
} else if (strstr(data[idxK], newtag) && !Found) {
Found = 1;
data[idxK][0] = '\0';
122 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
}
}
}
}
if(!Error){
printf("No errors detected!\n");
}
return 0;
}
2.41.1.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
clock_t actClock;
double actSec=0;
while (actSec < 11) {
actClock = clock();
actSec = (double)actClock / CLOCKS_PER_SEC;
printf("\n%lf", actSec);
}
return 0;
}
2.41.2.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
clock_t actClock;
double actSec=0;
int intActSec=0, intOldSec=0;
while (actSec < 11) {
actClock = clock();
actSec = (double)actClock / CLOCKS_PER_SEC;
intActSec = (int)actSec;
if (intActSec>intOldSec) {
printf("\n%d", intActSec);
intOldSec = intActSec;
}
}
return 0;
}
2.42.1.
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>

int main() {
struct _timeb timebuffer;
char* timeline;
int start, act;

_ftime(&timebuffer);
start = timebuffer.time;
do {
9. Megoldsok 123
Heckl Istvn, PE www.tankonyvtar.hu
_ftime(&timebuffer);
timeline = ctime(&timebuffer.time);
act = timebuffer.time;
printf("\n%.8s.%hu", &timeline[11], timebuffer.millitm);
} while (act-start < 10);
return 0;
}
2.43.1.
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

int main() {
clock_t start, end;
int wait;
char temp[50];
double actWait;

srand((unsigned)time(NULL));
printf("Press 'a' and enter to start the clock!\n");
printf("Do the same to stop it!\n");
printf("Type quit to end program!\n");
while (strcmp(temp, "quit") != 0) {
wait = rand()%4 + 1;
printf("\nWait for %d seconds!\n", wait);
printf("Begin: ");
scanf("%s", temp);
if (strcmp(temp, "quit")==0) break;
start = clock();
printf("End: ");
scanf("%s", temp);
end = clock();
actWait = (double)(end - start) / CLOCKS_PER_SEC;
printf("You have waited %6.2lf seconds instead of %d. ", actWait,
wait);
}
return 0;
}
2.44.1.
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

int main() {
int year, month, day, guessWeekDay, guessYearDay;
tm tmBuffer;
char string[30];

tmBuffer.tm_hour = 0;
tmBuffer.tm_min = 0;
tmBuffer.tm_sec = 0;
tmBuffer.tm_isdst = -1;

srand((unsigned)time(NULL));
year = rand()%40+1970;
124 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
month = rand()%12+1;
day = rand()%30+1;
tmBuffer.tm_year = year-1900;
tmBuffer.tm_mon = month;
tmBuffer.tm_mday = day;
printf("What is the day of the week on %d/%d %d?\n", month, day,
year);
printf("0 - Sunday, 1 - Monday, ...; your guess: ");
scanf("%d", &guessWeekDay);
mktime(&tmBuffer); // calculating week day and year day
strftime(string, 30, "%A", &tmBuffer);
if (tmBuffer.tm_wday == guessWeekDay) {
printf("You are rigth %d/%d %d is really %s.\n", month, day, year,
string);
} else {
printf("You are wrong %d/%d %d is %s.\n", month, day, year,
string);
}
printf("\nWhat is the day of the year on the same date? ");
scanf("%d", &guessYearDay);
if (tmBuffer.tm_yday == guessYearDay) {
printf("You are rigth %d/%d %d is the %d day of the year.\n",
month, day, year, tmBuffer.tm_yday);
} else {
printf("You are wrong %d/%d %d is the %d day of the year.\n",
month, day, year, tmBuffer.tm_yday);
}
return 0;
}
2.45.1.
#include <iostream>
#include <cmath>
using namespace std;

float heron(float a, float b, float c) {
if (a<=0)
throw a;
if (b<=0)
throw b;
if (c<=0)
throw c;
if (a>=b+c || b>=a+c || c>=a+b)
throw "No triangle can be constructed from the sides";
float s=(a+b+c)/2;
float result=sqrt(s*(s-a)*(s-b)*(s-c));
return result;
}

int main() {
cout << "The program will calculate the area of a triangle." << endl;
float area;
try {
area=heron(3, 2.54, 9);
} catch(float para) {
cout << "Triangle side can not be 0 or less, it is " << para <<
endl;
} catch(const char* msg) {
cout << msg << endl;
9. Megoldsok 125
Heckl Istvn, PE www.tankonyvtar.hu
} catch(...) {
cout << "Unknown error" << endl;
}
return 0;
}
2.46.1.
#include <iostream>
using namespace std;
class rightAngleTriangle {
private:
float a; // befogo
float b; // befogo
float c; // atfogo
public:
bool check() const;
float area() const;
float perimeter() const;
void display() const;

void setA(float para) {a=para;}
void setB(float para) {b=para;}
void setC(float para) {this->c=para;}
float getA() const {return a;}
float getB() const {return this->b;}
float getC() const {return c;}
};
bool rightAngleTriangle::check() const {
bool result=false;
if (a*a+b*b==c*c)
result=true;
return result;
}
float rightAngleTriangle::area() const {
float result=a*b/2;
return result;
}
float rightAngleTriangle::perimeter() const {
float result=a+b+c;
return result;
}
void rightAngleTriangle::display() const {
bool valid=check();
cout << boolalpha;
cout << "The triangle is valid: " << valid << endl;
if (valid)
cout << "The sides are: " << this->a << ", " << b << ", " <<
getC() << endl;
// see the different references to the data members
}
int main() {
rightAngleTriangle myObject;
myObject.setA(3);
myObject.setB(4);
myObject.setC(5);
myObject.display();
if (myObject.check()) {
cout << "Area: " << myObject.area() << endl;
cout << "Perimeter: " << myObject.perimeter() << endl;
126 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
return 0;
}
2.46.2.
#include <iostream>
using namespace std;
class isoscelesTriangle {
private:
float a; // befogo
float b; // befogo
float c; // atfogo
public:
bool check() const;
float area() const;
float perimeter() const;
void display() const;

void setA(float para) {a=para;}
void setB(float para) {b=para;}
void setC(float para) {this->c=para;}
float getA() const {return a;}
float getB() const {return this->b;}
float getC() const {return c;}
};
bool isoscelesTriangle::check() const {
bool result=false;
if (a==b || b==c || a==c)
result=true;
return result;
}
float isoscelesTriangle::area() const {
float s=(a+b+c)/2;
float result=s*(s-a)*(s-b);
return result;
}
float isoscelesTriangle::perimeter() const {
float result=a+b+c;
return result;
}
void isoscelesTriangle::display() const {
bool valid=check();
cout << boolalpha;
cout << "The triangle is valid: " << valid << endl;
if (valid)
cout << "The sides are: " << this->a << ", " << b << ", " <<
getC() << endl;
// see the different references to the data members
}
int main() {
isoscelesTriangle myObject;
myObject.setA(3);
myObject.setB(3);
myObject.setC(5);
myObject.display();
if (myObject.check()) {
cout << "Area: " << myObject.area() << endl;
cout << "Perimeter: " << myObject.perimeter() << endl;
}
9. Megoldsok 127
Heckl Istvn, PE www.tankonyvtar.hu
return 0;
}
2.46.3.
#include <iostream>
using namespace std;
class equilateralTriangle {
private:
float a; // befogo
float b; // befogo
float c; // atfogo
public:
bool check() const;
float area() const;
float perimeter() const;
void display() const;

void setA(float para) {a=para;}
void setB(float para) {b=para;}
void setC(float para) {this->c=para;}
float getA() const {return a;}
float getB() const {return this->b;}
float getC() const {return c;}
};
bool equilateralTriangle::check() const {
bool result=false;
if (a==b && b==c)
result=true;
return result;
}
float equilateralTriangle::area() const {
float s=(a+b+c)/2;
float result=s*(s-a)*(s-b);
return result;
}
float equilateralTriangle::perimeter() const {
float result=a+b+c;
return result;
}
void equilateralTriangle::display() const {
bool valid=check();
cout << boolalpha;
cout << "The triangle is valid: " << valid << endl;
if (valid)
cout << "The sides are: " << this->a << ", " << b << ", " <<
getC() << endl;
// see the different references to the data members
}
int main() {
equilateralTriangle myObject;
myObject.setA(3);
myObject.setB(3);
myObject.setC(5);
myObject.display();
if (myObject.check()) {
cout << "Area: " << myObject.area() << endl;
cout << "Perimeter: " << myObject.perimeter() << endl;
}
return 0;
128 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
2.47.1.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Counter {
char fileName[500];
ofstream file;
public:
static int lineCount;
void init(char* para);
void close() {file.close();}
void write(const char* line);
static int getLineCount() {return lineCount;}
static void resetLineCount() {lineCount=0;}
};

void Counter::init(char* para) {
strcpy(fileName, para);
file.open(fileName);
}

void Counter::write(const char* line) {
file << line << endl;
lineCount++;
}

int Counter::lineCount=0; // class variable def.

int main() {
Counter obj1, obj2;

cout << "The number of lines have written till now:" <<
Counter::lineCount << endl;
obj1.init("file1.txt");
obj1.write("The first line");
obj1.write("and the second");
cout << "The number of lines have written till now:" <<
obj1.lineCount << endl;
obj2.init("file2.txt");
obj2.write("New line");
cout << "The number of lines have written till now:" <<
obj2.lineCount << endl;
Counter::resetLineCount();
obj1.write("Strange line");
cout << "The number of lines have written till now:" <<
obj2.lineCount << endl;
obj1.close();
obj2.close();
return 0;
}
2.47.2.
#include <iostream>
#include <fstream>
#include <cstring>
9. Megoldsok 129
Heckl Istvn, PE www.tankonyvtar.hu
using namespace std;

class Counter {
char fileName[500];
ofstream file;
public:
static int lineCount;
static int wordCount;
static int charCount;
void init(const char* para);
void close() {file.close();}
void write(const char* line);
};

void Counter::init(const char* para) {
strcpy(fileName, para);
file.open(fileName);
}

void Counter::write(const char* line) {
int i=0;
while (line[i]!='\0') {
file << line[i];
charCount++;
if (line[i]==' ') { wordCount++; }
i++;
}
if (line[0]!='\0') { wordCount++; }
file << endl;
lineCount++;
}

int Counter::lineCount=0; // class variable def.
int Counter::wordCount=0; // class variable def.
int Counter::charCount=0; // class variable def.

int main() {
Counter obj1, obj2;

cout << "The number of lines have written till now:" <<
Counter::lineCount << endl;
obj1.init("file1.txt");
obj1.write("The first line");
obj1.write("and the second");
cout << "The number of lines have written till now:" <<
obj1.lineCount << endl;
obj2.init("file2.txt");
obj2.write("New line");
cout << "The number of lines have written till now:" <<
obj2.lineCount << endl;
obj2.lineCount=0;
obj1.write("Strange line");
cout << "The number of lines have written till now:" <<
obj2.lineCount << endl;
obj1.close();
obj2.close();
return 0;
}
130 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.48.1.
#include <iostream>
#include <cstring>
using namespace std;

class Complex {
float real, im;
Complex multiply(const Complex&) const;
public:
void setReal(float para) {real=para;}
void setIm(float para) {im=para;}
float getReal() const {return real;}
float getIm() const {return im;}
void display() const;
void sum(const Complex&) const;
void sub(const Complex&) const;
void mul(const Complex&) const;
void div(const Complex&) const;
};

void Complex::sum(const Complex& para) const {
float resultReal, resultIm;
resultReal=real+para.real;
resultIm=im+para.im;
cout << resultReal << "+" << resultIm << "i";
}

void Complex::sub(const Complex& para) const {
float resultReal, resultIm;
resultReal=real-para.real;
resultIm=im-para.im;
cout << resultReal << "+" << resultIm << "i";
}

void Complex::mul(const Complex& para) const {
float resultReal, resultIm;
resultReal=real*para.real - im*para.im;
resultIm=im*para.real+real*para.im;
cout << resultReal << "+" << resultIm << "i";
}

Complex Complex::multiply(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real*para.real - im*para.im;
resultIm=im*para.real+real*para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

void Complex::div(const Complex& para) const {
float resultReal, resultIm;
if (para.real==0 && para.im==0) {
cout << "Error: divison by zero." << endl;
return;
}
Complex recip;
9. Megoldsok 131
Heckl Istvn, PE www.tankonyvtar.hu
recip.real=para.real/(para.real*para.real+para.im*para.im);
recip.setIm(-para.im/(para.real*para.real+para.im*para.im));
Complex result=this->multiply(recip);
resultReal=result.getReal();
resultIm=result.im;
cout << resultReal << "+" << resultIm << "i";
}

void Complex::display() const {
cout << real << "+" << im << "i";
}

int main() {
Complex a, b;

a.setReal(1);
a.setIm(2);
b.setReal(3);
b.setIm(4);
a.display(); cout << " + "; b.display(); cout << "="; a.sum(b); cout
<< endl;
a.display(); cout << " - "; b.display(); cout << "="; a.sub(b); cout
<< endl;
a.display(); cout << " * "; b.display(); cout << "="; a.mul(b); cout
<< endl;
a.display(); cout << " / "; b.display(); cout << "="; a.div(b); cout
<< endl;
return 0;
}
2.48.2.
#include <iostream>
#include <cstring>
using namespace std;

class Complex {
float real, im;
Complex multiply(const Complex&) const;
public:
void setReal(float para) {real=para;}
void setIm(float para) {im=para;}
float getReal() const {return real;}
float getIm() const {return im;}
void display() const;
Complex sum(const Complex&) const;
Complex sub(const Complex&) const;
Complex mul(const Complex&) const;
Complex div(const Complex&) const;
friend ostream& operator <<(ostream &os,const Complex &obj);
};

ostream& operator <<(ostream &os,const Complex &obj) {
os<< "(" << obj.real << " + " << obj.im << "i)";
return os;
}

Complex Complex::sum(const Complex& para) const {
float resultReal, resultIm;
Complex result;
132 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
resultReal=real+para.real;
resultIm=im+para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::sub(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real-para.real;
resultIm=im-para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::mul(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real*para.real - im*para.im;
resultIm=im*para.real+real*para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::multiply(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real*para.real - im*para.im;
resultIm=im*para.real+real*para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::div(const Complex& para) const {
float resultReal, resultIm;
Complex result;
if (para.real==0 && para.im==0) {
cout << "Error: divison by zero." << endl;
return result;
}
Complex recip;
recip.real=para.real/(para.real*para.real+para.im*para.im);
recip.setIm(-para.im/(para.real*para.real+para.im*para.im));
result=this->multiply(recip);
resultReal=result.getReal();
resultIm=result.im;
return result;
}

void Complex::display() const {
cout << real << " + " << im << "i";
}

int main() {
Complex a, b;
9. Megoldsok 133
Heckl Istvn, PE www.tankonyvtar.hu

a.setReal(1);
a.setIm(2);
b.setReal(3);
b.setIm(4);
cout << a << " + " << b << "=" << a.sum(b) << endl;
cout << a << " - " << b << "=" << a.sub(b) << endl;
cout << a << " * " << b << "=" << a.mul(b) << endl;
cout << a << " / " << b << "=" << a.div(b) << endl;
return 0;
}
2.48.3.
#include <iostream>
#include <cstring>
using namespace std;

class Complex {
float real, im;
Complex multiply(const Complex&) const;
public:
void setReal(float para) {real=para;}
void setIm(float para) {im=para;}
float getReal() const {return real;}
float getIm() const {return im;}
void display() const;
Complex sum(const Complex&) const;
Complex sub(const Complex&) const;
Complex mul(const Complex&) const;
Complex div(const Complex&) const;
friend ostream& operator <<(ostream &os,const Complex &obj);
const Complex operator+(const Complex &other) const {
Complex result = sum(other);
return result;
}
const Complex operator-(const Complex &other) const {
Complex result = sub(other);
return result;
}
const Complex operator*(const Complex &other) const {
Complex result = mul(other);
return result;
}
const Complex operator/(const Complex &other) const {
Complex result = div(other);
return result;
}
};

ostream& operator <<(ostream &os,const Complex &obj) {
os<< "(" << obj.real << " + " << obj.im << "i) ";
return os;
}

Complex Complex::sum(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real+para.real;
resultIm=im+para.im;
134 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::sub(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real-para.real;
resultIm=im-para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::mul(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real*para.real - im*para.im;
resultIm=im*para.real+real*para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::multiply(const Complex& para) const {
float resultReal, resultIm;
Complex result;
resultReal=real*para.real - im*para.im;
resultIm=im*para.real+real*para.im;
result.real=resultReal;
result.setIm(resultIm);
return result;
}

Complex Complex::div(const Complex& para) const {
float resultReal, resultIm;
Complex result;
if (para.real==0 && para.im==0) {
cout << "Error: divison by zero." << endl;
return result;
}
Complex recip;
recip.real=para.real/(para.real*para.real+para.im*para.im);
recip.setIm(-para.im/(para.real*para.real+para.im*para.im));
result=this->multiply(recip);
resultReal=result.getReal();
resultIm=result.im;
return result;
}

void Complex::display() const {
cout << real << " + " << im << "i";
}

int main() {
Complex a, b;

a.setReal(1);
9. Megoldsok 135
Heckl Istvn, PE www.tankonyvtar.hu
a.setIm(2);
b.setReal(3);
b.setIm(4);
cout << a << " + " << b << "=" << a + b << endl;
cout << a << " - " << b << "=" << a - b << endl;
cout << a << " * " << b << "=" << a * b << endl;
cout << a << " / " << b << "=" << a / b << endl;
return 0;
}
2.49.1.
#include <stdio.h>
#include <stdlib.h>

#define NEV_HOSZ 11
#define INPUT_FILE "in.txt"

struct TSubscriber
{
char FirstName[NEV_HOSZ];
char LastName[NEV_HOSZ];
int InRushH, OutRushH;
int TotalMin, Fee;
};

void read(FILE * fd, int num, struct TSubscriber * Subscribers)
{
int i;

for (i = 0; i < num; i++)
{
fscanf(fd, "%s %s", Subscribers[i].FirstName,
Subscribers[i].LastName);
fscanf(fd, "%d %d", &Subscribers[i].InRushH,
&Subscribers[i].OutRushH);
}
}

void calc(int num, struct TSubscriber * A, int csucs, int kedv)
{
int i;
int MaxMin = 0;
int MaxFee = 0;
for (i = 0; i < num; i++)
{
A[i].Fee = A[i].InRushH * csucs + A[i].OutRushH * kedv;
A[i].TotalMin = A[i].InRushH + A[i].OutRushH;
printf("\t\t\t %5d Ft %5d minute\r%s %s :\n", A[i].Fee,
A[i].TotalMin,
A[i].FirstName, A[i].LastName);
if (MaxMin < A[i].TotalMin)
MaxMin = A[i].TotalMin;
if (MaxFee < A[i].Fee)
MaxFee = A[i].Fee;
}
printf("\nHighest fee: %d Ft\n", MaxFee);
for (i=0; i<num; i++)
{
if (A[i].Fee == MaxFee)
136 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("\t%s %s\n", A[i].FirstName, A[i].LastName);
}
printf("\nLongest speaking: %d Ft\n", MaxMin);
for (i=0; i<num; i++)
{
if (A[i].TotalMin == MaxMin)
printf("\t%s %s\n",A[i].FirstName, A[i].LastName);
}
}

int main()
{
struct TSubscriber * Subscribers = NULL;
int inrush, outrush, num;
FILE * fd = fopen(INPUT_FILE, "r");
if (fd == NULL)
{
perror("Hiba");
return 0;
}
fscanf(fd, "%d", &num);
fscanf(fd, "%d %d", &inrush,&outrush);
Subscribers = (struct TSubscriber *)malloc(num * sizeof(struct
TSubscriber));

read(fd, num, Subscribers );
fclose(fd);

calc(num, Subscribers, inrush, outrush);
free(Subscribers);
Subscribers = NULL;

return 0;
}
2.50.1.
#include <stdio.h>
#include <stdlib.h>

#define INPUT_FILE "sets.txt"
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))

void ReadSet(FILE * fd, int * size, int ** set)
{
int i;
fscanf(fd, "%d", size);
*set = (int *)malloc(sizeof(int) * (*size) );
for (i = 0; i < *size; i++)
fscanf(fd, "%d", *set + i);
printf("\n");
}

void PrintSet(char * name, int size, int * set)
{
int i;
printf("%s = ", name);
printf("{");
for (i = 0; i < size - 1; i++)
9. Megoldsok 137
Heckl Istvn, PE www.tankonyvtar.hu
printf("%d, ", set[i]);
if (size > 0)
printf("%d", set[size - 1]);
printf("}\n");
}

int Element(int e, int size, int * S)
{
int i = 0;
while ((i < size) && (S[i] != e))
i++;
return i < size;
}

void Intersection(int SizeA, int SizeB, int * SizeI, int * SA, int * SB,
int ** C)
{
int size = 0;
int i;
*SizeI = 0;

int * A = SizeA > SizeB ? SA : SB;
int * B = SizeA > SizeB ? SB : SA;

for (i = 0; i < max(SizeA, SizeB); i++)
{

if (Element(A[i], max(SizeA, SizeB), A) && Element(A[i], min(SizeA,
SizeB), B) )
(*SizeI)++;
}

*C = (int *)malloc(sizeof(int) * (*SizeI) );
for (i = 0; i < max(SizeA, SizeB); i++)
{

if (Element(A[i], max(SizeA, SizeB), A) && Element(A[i], min(SizeA,
SizeB), B) )
(*C)[size++] = A[i];
}
}

int IsSubset(int SizeA, int SizeS, int * A, int * S)
{
int i;
if (SizeS > SizeA)
return 0;
for (i = 0; i < SizeS; i++)
if (!Element(S[i], SizeA, A))
return 0;
return 1;
}

int main(int argc, char *argv[])
{
int SetASize, SetBSize, SetISize;
int * SetA;
int * SetB;
int * SetI;
138 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int num;
FILE * fd = fopen(argc > 1 ? argv[1] : INPUT_FILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadSet(fd, &SetASize, &SetA);
ReadSet(fd, &SetBSize, &SetB);
fclose(fd);
Intersection(SetASize, SetBSize, &SetISize, SetA, SetB, &SetI);

printf("Type a number: ");
scanf("%d", &num);
if (Element(num, SetASize, SetA))
printf("%d is element of A\n", num);
else
printf("%d is not element of A\n", num);

if (Element(num, SetBSize, SetB))
printf("%d is element of B\n", num);
else
printf("%d is not element of B\n", num);

if (Element(num, SetISize, SetI))
printf("%d is element of intersection of A and B\n", num);
else
printf("%d is not element of intersection of A and B\n", num);

PrintSet("A", SetASize, SetA);
PrintSet("B", SetBSize, SetB);
PrintSet("Intersection of A and B", SetISize, SetI);
if (IsSubset(SetASize, SetBSize, SetA, SetB))
printf("B is subset of A\n");
else
printf("B is not subset of A\n");
if (IsSubset(SetBSize, SetASize, SetB, SetA))
printf("A is subset of B\n");
else
printf("A is not subset of B\n");

free(SetA); SetA = NULL;
free(SetB); SetB = NULL;
free(SetI); SetI = NULL;
return 0;
}
2.51.1.
#include <stdio.h>
#include <stdlib.h>

#define INPUT_FILE "sets.txt"
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))

void ReadSet(FILE * fd, int * size, int ** set)
{
int i;
fscanf(fd, "%d", size);
9. Megoldsok 139
Heckl Istvn, PE www.tankonyvtar.hu
*set = (int *)malloc(sizeof(int) * (*size) );
for (i = 0; i < *size; i++)
fscanf(fd, "%d", *set + i);
printf("\n");
}

void PrintSet(char * name, int size, int * set)
{
int i;
printf("%s = ", name);
printf("{");
for (i = 0; i < size - 1; i++)
printf("%d, ", set[i]);
if (size > 0)
printf("%d", set[size - 1]);
printf("}\n");
}

int Element(int e, int size, int * S)
{
int i = 0;
while ((i < size) && (S[i] != e))
i++;
return i < size;
}

void Union(int SizeA, int SizeB, int * SizeU, int * SA, int * SB, int **
C)
{
int size = max(SizeA, SizeB);
int i;
*SizeU = 0;
int * A = SizeA > SizeB ? SA : SB;
int * B = SizeA > SizeB ? SB : SA;

for (i = 0; i < min(SizeA, SizeB); i++)
{
if ( !Element(B[i], max(SizeA, SizeB), A) )
size++;
}
*C = (int *)malloc(sizeof(int) * size );
*SizeU = size;
for (i = 0; i < max(SizeA, SizeB); i++)
(*C)[i] = A[i];

size = max(SizeA, SizeB);
for (i = 0; i < min(SizeA, SizeB); i++)
{
if ( !Element(B[i], max(SizeA, SizeB), A) )
(*C)[size++] = B[i];
}
}

int IsSubset(int SizeA, int SizeS, int * A, int * S)
{
int i;
if (SizeS > SizeA)
return 0;
for (i = 0; i < SizeS; i++)
140 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
if (!Element(S[i], SizeA, A))
return 0;
return 1;
}

int main(int argc, char *argv[])
{
int SetASize, SetBSize, SetUSize;
int * SetA;
int * SetB;
int * SetU;
int num;
FILE * fd = fopen(argc > 1 ? argv[1] : INPUT_FILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadSet(fd, &SetASize, &SetA);
ReadSet(fd, &SetBSize, &SetB);
fclose(fd);
Union(SetASize, SetBSize, &SetUSize, SetA, SetB, &SetU);


printf("Type a number: ");
scanf("%d", &num);
if (Element(num, SetASize, SetA))
printf("%d is element of A\n", num);
else
printf("%d is not element of A\n", num);

if (Element(num, SetBSize, SetB))
printf("%d is element of B\n", num);
else
printf("%d is not element of B\n", num);

if (Element(num, SetUSize, SetU))
printf("%d is element of union of A and B\n", num);
else
printf("%d is not element of union of A and B\n", num);


PrintSet("A", SetASize, SetA);
PrintSet("B", SetBSize, SetB);
PrintSet("Union of A and B", SetUSize, SetU);
if (IsSubset(SetASize, SetBSize, SetA, SetB))
printf("B is subset of A\n");
else
printf("B is not subset of A\n");
if (IsSubset(SetBSize, SetASize, SetB, SetA))
printf("A is subset of B\n");
else
printf("A is not subset of B\n");

free(SetA); SetA = NULL;
free(SetB); SetB = NULL;
free(SetU); SetU = NULL;
return 0;
}
9. Megoldsok 141
Heckl Istvn, PE www.tankonyvtar.hu
2.52.1.
#include <stdio.h>
#include <stdlib.h>

#define INPUT_FILE "sets.txt"
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))

void ReadSet(FILE * fd, int * size, int ** set)
{
int i;
fscanf(fd, "%d", size);
*set = (int *)malloc(sizeof(int) * (*size) );
for (i = 0; i < *size; i++)
fscanf(fd, "%d", *set + i);
printf("\n");
}

void PrintSet(char * name, int size, int * set)
{
int i;
printf("%s = ", name);
printf("{");
for (i = 0; i < size - 1; i++)
printf("%d, ", set[i]);
if (size > 0)
printf("%d", set[size - 1]);
printf("}\n");
}

int Element(int e, int size, int * S)
{
int i = 0;
while ((i < size) && (S[i] != e))
i++;
return i < size;
}

// A \ B
void SetDifference(int SizeA, int SizeB, int * SizeD, int * SA, int * SB,
int ** C)
{
int size = 0;
int i;
for (i = 0; i < SizeA; i++)
{
if (!Element(SA[i], SizeB, SB))
size++;
}
*C = (int *)malloc(sizeof(int) * size);
*SizeD = size;
size = 0;
for (i = 0; i < SizeA; i++)
{
if (!Element(SA[i], SizeB, SB))
(*C)[size++] = SA[i];
}
}
142 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

int IsSubset(int SizeA, int SizeS, int * A, int * S)
{
int i;
if (SizeS > SizeA)
return 0;
for (i = 0; i < SizeS; i++)
if (!Element(S[i], SizeA, A))
return 0;
return 1;
}

int main(int argc, char *argv[])
{
int SetASize, SetBSize, SetD1Size, SetD2Size;
int * SetA;
int * SetB;
int * SetD1;
int * SetD2;
int num;
FILE * fd = fopen(argc > 1 ? argv[1] : INPUT_FILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadSet(fd, &SetASize, &SetA);
ReadSet(fd, &SetBSize, &SetB);
fclose(fd);

SetDifference(SetASize, SetBSize, &SetD1Size, SetA, SetB, &SetD1);
SetDifference(SetBSize, SetASize, &SetD2Size, SetB, SetA, &SetD2);

printf("Type a number: ");
scanf("%d", &num);
if (Element(num, SetASize, SetA))
printf("%d is element of A\n", num);
else
printf("%d is not element of A\n", num);

if (Element(num, SetBSize, SetB))
printf("%d is element of B\n", num);
else
printf("%d is not element of B\n", num);

if (Element(num, SetD1Size, SetD1))
printf("%d is element of A \\ B\n", num);
else
printf("%d is not element of A \\ B\n", num);

if (Element(num, SetD2Size, SetD2))
printf("%d is element of B \\ A\n", num);
else
printf("%d is not element of B \\ A\n", num);

PrintSet("A", SetASize, SetA);
PrintSet("B", SetBSize, SetB);
PrintSet("Set difference A\\B", SetD1Size, SetD1);
PrintSet("Set difference B\\A", SetD2Size, SetD2);
9. Megoldsok 143
Heckl Istvn, PE www.tankonyvtar.hu
if (IsSubset(SetASize, SetBSize, SetA, SetB))
printf("B is subset of A\n");
else
printf("B is not subset of A\n");
if (IsSubset(SetBSize, SetASize, SetB, SetA))
printf("A is subset of B\n");
else
printf("A is not subset of B\n");

free(SetA); SetA = NULL;
free(SetB); SetB = NULL;
free(SetD1); SetD1 = NULL;
free(SetD2); SetD2 = NULL;
return 0;
}
2.53.1.
#include <stdio.h>
#include <stdlib.h>

typedef unsigned long int ULint;

ULint BinomialCoefficient(int n, int k)
{
ULint bc = n;
int i;
if (k == 0)
return 1;
for (i = n - 1 ; i > (n - k); i--)
{
bc *= i;
// printf("%d %ld\n", i, bc);
}
for (i = 2; i <= k; i++)
bc /= i;
return bc;
}

void PrintPow(char ch, int p)
{
if (p == 0)
return;
if (p == 1)
printf("%c", ch);
else
printf("%c^%d", ch, p);
}

void PrintBinom(int a)
{
int i;
int b;
printf("( a + b )^%d = ", a);
for (i = 0; i <= a; i++)
{
b = BinomialCoefficient(a, i);
if (b > 1)
printf("%d", b);
PrintPow('b', i);
144 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
PrintPow('a', a - i);
if (i < a)
printf(" + ");
}
printf("\n");
}

int main(int argc, char * argv[] )
{
int a;
if (argc > 1)
a = atoi(argv[1]);
else
{
printf(Degree: );
scanf("%d", &a);
}
printf("\n");
PrintBinom(a);
printf("\n");
return 0;
}
2.54.1.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MIN_TIP 1
#define EASY_MAX 5
#define MEDIUM_MAX 10
#define HARD_MAX 15
#define START_MONEY 1000

int GetStake()
{
int stake;
do
{
printf("Take your stake: ");
scanf("%d", &stake);
if (stake <= 0)
printf("The stake have to higher than zero!\n");
} while (stake <= 0);
return stake;
}

int GetTip(int min, int max)
{
int tip;
do
{
printf("What's your tip (%d..%d)? ", min, max);
scanf("%d", &tip);
if ((tip > max) || (tip < min))
printf("The tip have to be between %d and %d!\n", min, max);
} while ((tip > max) || (tip < min));
return tip;
}
9. Megoldsok 145
Heckl Istvn, PE www.tankonyvtar.hu

int GetMax()
{
int d;
do
{
printf("Choose the difficulty!\n\n");
printf("\tEasy:...........1\n");
printf("\tMedium:.........2\n");
printf("\tHard:...........3\n\n");
scanf("%d", &d);
if ((d > 3) || (d < 1))
printf("Wrong number!\n");
} while ((d > 3) || (d < 1));
switch (d)
{
case 1:
return EASY_MAX;
case 2:
return MEDIUM_MAX;
case 3:
return HARD_MAX;
}
return 0;
}

int Random(int min, int max)
{
return (rand() % (max - min)) + min;
}

int main()
{
int stake, tip;
int max;
int num;
int Money = START_MONEY;
char s[5];
srand(time(NULL));
max = GetMax();
printf("You have %d HUF now.\n", Money);
do
{
printf("\n\n");
stake = GetStake();
num = Random(MIN_TIP, max);
tip = GetTip(MIN_TIP, max);

if (tip == num)
{
Money += stake;
printf("You've hit the number!\nYou have %d HUF!\n", Money);
} else
{
printf("The number was %d\n", num);
Money -= stake;
printf("You have %d HUF!\n", Money);
}
if (Money > 0)
146 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
{
printf("Try again? (y/n)\n");
scanf("%s", s);
}
} while (((s[0] == 'y') || (s[0] == 'Y')) && (Money > 0));
if (Money > 0)
printf("Congratulations!\nYou get %d HUF!\n", Money);
else
printf("I'm sorry, you lost\n");
srand(time(NULL));
return 0;
}
2.55.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "date.txt"
#define DOT '.'
#define MAX_LENGTH 10

struct TDate
{
char Year[MAX_LENGTH];
char Month[MAX_LENGTH];
char Day[MAX_LENGTH];
};

void InitDate(struct TDate * Date)
{
Date->Year[0] = Date->Month[0] = Date->Day[0] = 0;
}

void ReadDate(FILE * fd, struct TDate * Date)
{
fscanf(fd, "%s", Date->Year);
fscanf(fd, "%s", Date->Month);
fscanf(fd, "%s", Date->Day);
}

void PrintDate(struct TDate * Date)
{
printf("%s %s %s\n", Date->Year, Date->Month, Date->Day);
}

int CheckNumAndDots(char * S, char * A)
{
int i;
int len = strlen(S);
int errnum = 0;
/* Check numbers: */
for (i = 0; i < len - 1; i++)
{
if ((S[i] > '9') || (S[i] < '0'))
{
errnum++;
printf("Error: the %s cannot contain %c character!\n", A,
S[i]);
9. Megoldsok 147
Heckl Istvn, PE www.tankonyvtar.hu
}
}
/* Check dot: */
if (S[len - 1] != DOT)
{
errnum++;
printf("Error: A \"%c\" have to follow the number, not
\%c\!\n", DOT, S[len - 1]);
}
return errnum;
}

int CheckNums(struct TDate * Date)
{
int errnum = 0;
int month = atoi(Date->Month);
int day = atoi(Date->Day);
if ((month > 12) || (month < 1))
{
errnum++;
printf("Error: There are only 12 months!\n");
}
if ((day > 31) || (day < 1))
{
errnum++;
printf("Error: There are atmost 31, at least 1 days in a
month!\n");
}
return errnum;
}

void CheckDate(struct TDate * Date)
{
int errnum = CheckNumAndDots(Date->Year, "Year");
errnum += CheckNumAndDots(Date->Month, "Month");
errnum += CheckNumAndDots(Date->Day, "Day");
if (errnum == 0)
errnum += CheckNums(Date);
printf("*******************************\nI found %d errors\n",
errnum);
}

int main(int argc, char *argv[])
{
struct TDate Date;
InitDate(&Date);
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == 0)
{
perror("Error");
return 0;
}
ReadDate(fd, &Date);
PrintDate(&Date);
CheckDate(&Date);
fclose(fd);
return 0;
}
148 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
2.55.2.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "date.txt"
#define YEAR_MIN 1000
#define YEAR_MAX 3000
#define MONTH_MAX 12
#define DAY_MAX 31

const char * Months_Strings[12] = { "January", "February", "March",
"April", "May", "June",
"July", "August", "September", "October", "November", "December"
};

enum Months{ jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov,
dec};

struct TDate
{
int Year;
int Month;
int Day;
};

void ReadDate(FILE * fd, struct TDate * Date)
{
fscanf(fd, "%d.", &Date->Year);
fscanf(fd, "%d.", &Date->Month);
fscanf(fd, "%d.", &Date->Day);
}

void PrintDate(struct TDate * Date)
{
printf("Year: %d\nMonth: %s\nDay: %d\n", Date->Year,
((Date->Month >= 1) && (Date->Month <= 12)) ?
Months_Strings[Date->Month - 1]
: "Bad month", Date->Day);
}

int CheckYear(int Y)
{
int errnum = 0;
if (Y > YEAR_MAX)
{
errnum++;
printf("Error: %d is too high for the year!\n", Y);
}
if (Y < YEAR_MIN)
{
errnum++;
printf("Error: %d is too low for the year!\n", Y);
}
return errnum;
}

int CheckMonth(int M)
{
9. Megoldsok 149
Heckl Istvn, PE www.tankonyvtar.hu
int errnum = 0;
if (M > MONTH_MAX)
{
errnum++;
printf("Error: %d is too high for the month!\n", M);
}
if (M < 1)
{
errnum++;
printf("Error: %d is too low for the month!\n", M);
}
return errnum;
}

int LeapYear(int y)
{
if (y % 4 == 0)
{
if (y % 100 == 0)
{
if (y % 400 == 0)
return 1;
else
return 0;
} else return 1;
}
return 0;
}

int CheckDay(struct TDate * Date)
{
int errnum = 0;
switch (Date->Month)
{
case jan:
case mar:
case may:
case jul:
case aug:
case oct:
case dec:
if (Date->Day > 31)
{
errnum++;
printf("Error: In %s there are 31 days!\n",
Months_Strings[ Date-> Month - 1]);
}
break;
case apr:
case jun:
case sep:
case nov:
if (Date->Day > 30)
{
errnum++;
printf("Error: In %s there are 30 days!\n",
Months_Strings[ Date-> Month - 1]);
}
break;
150 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
case feb:
/* Leap year? */
if (LeapYear(Date->Year))
{
if (Date->Day > 29)
{
errnum++;
printf("Error: In %dth %s there are 29 days!\n",
Date->Year,
Months_Strings[ Date-> Month - 1 ]);
}
} else
{
if (Date->Day > 28)
{
errnum++;
printf("Error: In %dth %s there are 28 days!\n",
Date->Year,
Months_Strings[ Date-> Month - 1 ]);
}
}
break;
}
return errnum;
}


void CheckDate(struct TDate * Date)
{
int errnum = CheckYear(Date->Year);
errnum += CheckMonth(Date->Month);
if (!errnum)
errnum = CheckDay(Date);
printf("*******************************\nI found %d errors\n",
errnum);
}

int main(int argc, char *argv[])
{
struct TDate Date;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == 0)
{
perror("Error");
return 0;
}
ReadDate(fd, &Date);
PrintDate(&Date);
CheckDate(&Date);
fclose(fd);
return 0;
}
2.56.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_ROWNUM 10
#define SZOKOZS 4
9. Megoldsok 151
Heckl Istvn, PE www.tankonyvtar.hu

int BinomialCoefficient(int n, int k)
{
int bc = n;
int i;
if (k == 0)
return 1;
for (i = n - 1 ; i > (n - k); i--)
{
bc *= i;
}
for (i = 2; i <= k; i++)
bc /= i;
return bc;
}

int GetWidth(int n)
{
return n * 3 + (n - 1) * SZOKOZS;
}

void PascalsTriangle(int rows)
{
int i, sp, r, j;
int width = GetWidth(rows);
for (r = 0; r < rows; r++)
{
for (sp = 0; sp < (width / 2) - (GetWidth(r) / 2); sp++)
printf("");
for (i = 0; i <= r; i++)
{
printf("%3d", BinomialCoefficient(r, i));
for (j = 0; j < SZOKOZS; j++)
printf("");
}

printf("\n");
}
}

int main(int argc, char * argv[])
{
int rows = argc > 1 ? atoi(argv[1]) : DEFAULT_ROWNUM;
PascalsTriangle(rows);
return 0;
}
2.57.1.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define DEFAULT_INPUTFILE "tipp1.txt"

void GetNumbers(int * A)
{
int i, j, num;
for (i = 0; i < 5; i++)
{
152 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
do
{
num = rand() % 90 + 1;
j = 0;
while ((j < i) && (A[j] != num))
j++;
} while (j < i);
A[i] = num;
}
}

void PrintNumbers(int * A)
{
int i;
for (i = 0; i < 4; i++)
printf("%d, ", A[i]);
printf("%d\n", A[4]);
}

void Check(FILE * fd, int * A, int * H)
{
int i, j, k, c, num, a;
fscanf(fd, "%d", &c);
for (k = 0; k < c; k++)
{
a = 0;
for (i = 0; i < 5; i++)
{
fscanf(fd, "%d", &num);
j = 0;
while ((j < 5) && (A[j] != num))
j++;
if (j < 5)
a++;
}
if (a > 0)
H[a - 1]++;
}
}

void InitHits(int * A)
{
int i;
for (i = 0; i < 5; i++)
A[i] = 0;
}

void PrintHits(int * A)
{
int i;
for (i = 0; i < 5; i++)
{
printf("There ");
if (A[i] > 1)
printf("are ");
else
printf("is ");
printf("%d %d hit", A[i], i + 1);
if (A[i] > 1)
9. Megoldsok 153
Heckl Istvn, PE www.tankonyvtar.hu
printf("s\n");
else
printf("\n");
}
}

int main(int argc, char * argv[])
{
int Numbers[5];
int Hits[5];
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, r);
if (fd == NULL)
{
perror("Error");
return 0;
}
srand(time(NULL));
InitHits(Hits);
GetNumbers(Numbers);
printf("Generated numbers: ");
PrintNumbers(Numbers);
Check(fd, Numbers, Hits);
PrintHits(Hits);
fclose(fd);
return 0;
}
2.58.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_RINGNUM 3
#define TRUE 1
#define FALSE 0
#define NAMELEN 12

struct TTower
{
int MaxHeight;
int Height;
int * Disks;
char Name[NAMELEN];
};

void InitTower(struct TTower * T, int height, int full, char * name)
{
int i;
T->Disks = (int*)malloc(sizeof(int) * height);
T->MaxHeight = height;
strcpy(T->Name, name);
if (full)
{
for (i = height; i >= 1; i--)
T->Disks[height - i] = i;
T->Height = height;
} else
{
for (i = 0; i < height; i++)
T->Disks[i] = 0;
154 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
T->Height = 0;
}
}

void FreeTower(struct TTower * T)
{
free(T->Disks);
T->Disks = NULL;
T->Height = T->MaxHeight = 0;
}

void PrintTower(struct TTower * T)
{
int i;
printf("%s: ", T->Name);
for (i = 0; i < T->Height - 1; i++)
printf("%d, ", T->Disks[i]);
printf("%d\n", T->Disks[i]);
}

int GetIndex(char * S)
{
if (strcmp(S, "src") == 0)
return 0;
if (strcmp(S, "aux") == 0)
return 1;
if (strcmp(S, "dst") == 0)
return 2;
return -1;
}

int IsCorrect(int f, int t, struct TTower * Towers)
{
if ((f == -1) || (t == -1))
return FALSE;
if (f == t)
return FALSE;
if (Towers[f].Height == 0)
return FALSE;
if (Towers[f].Disks[Towers[f].Height - 1] >
Towers[t].Disks[Towers[t].Height - 1])
return FALSE;
return TRUE;
}

int isComplete(struct TTower * T)
{
int i;
for (i = T->MaxHeight; i >= 1; i--)
if (T->Disks[ T->MaxHeight - i] != i)
return FALSE;
return TRUE;
}

int main(int argc, char * argv[])
{
char From[5];
char To[5];
int f, t;
9. Megoldsok 155
Heckl Istvn, PE www.tankonyvtar.hu
int giveup;
struct TTower Towers[3];
int MaxH = argc > 1 ? atoi(argv[1]) : DEFAULT_RINGNUM;
InitTower(Towers, MaxH, TRUE, "Source");
InitTower(Towers + 1, MaxH, FALSE, "Auxiliary");
InitTower(Towers + 2, MaxH, FALSE, "Destination");
do
{
printf("\n\n*************************************\n\n");
PrintTower(Towers);
PrintTower(Towers + 1);
PrintTower(Towers + 2);
printf("From: ");
scanf("%s", From);
if (From[0] != '0')
{
printf("To: ");
scanf("%s", To);
}
giveup = ((From[0] == '0') || (To[0] == '0'));
if (!giveup)
{
f = GetIndex(From);
t = GetIndex(To);
if (IsCorrect(f, t, Towers))
{
Towers[t].Disks[Towers[t].Height++] =
Towers[f].Disks[Towers[f].Height - 1];
Towers[f].Disks[--Towers[f].Height] = 0;
} else printf("Incorrect step!\n");
}
} while ((!giveup) && !isComplete(Towers + 2));
if (!giveup)
printf("The disks are on their's place!\n");
else
printf("The disks are not on the destination!\n");

printf("\n\n*************************************\n\n");
PrintTower(Towers);
PrintTower(Towers + 1);
PrintTower(Towers + 2);
FreeTower(Towers);
FreeTower(Towers + 1);
FreeTower(Towers + 2);
return 0;
}
2.59.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "nums.txt"

int Eukl(int a, int b)
{
int m = b;
while (m != 0)
{
b = m;
156 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
m = a % b;
a = b;
}
return b;
}

void ReadAndAdd(FILE * fd)
{
int count, i;
int num1, num2;
int den = 0, numer = 0;
int tmp1, tmp2;
int d;
fscanf(fd, "%d", &count);
for (i = 0; i < count; i++)
{
fscanf(fd, "%d %d", &num1, &num2);
if (den != 0)
{
tmp2 = den * num2;
tmp1 = num2 * numer + den * num1;
d = Eukl(tmp1, tmp2);
if (d != 1)
{
printf("%4d %4d %4d %4d\n", numer, num1, tmp1,
tmp1 / d);
printf("------ + ------ = ------ = ------\n");
printf("%4d %4d %4d %4d\n\n", den, num2, tmp2,
tmp2 / d);
} else
{
printf("%4d %4d %4d\n", numer, num1, tmp1);
printf("------ + ------ = ------\n");
printf("%4d %4d %4d\n\n", den, num2, tmp2);
}
numer = tmp1 / d;
den = tmp2 / d;
}else
{
den = num2;
numer = num1;
}

}
}

int main(int argc, char * argv[])
{
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, r);
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadAndAdd(fd);
fclose(fd);
return 0;
}
9. Megoldsok 157
Heckl Istvn, PE www.tankonyvtar.hu
2.60.1-2.60.4.
#include <stdio.h>
#include <stdlib.h>

int osztokOsszege(int szam) {
if (szam == 1) {
return 0;
}
int oszto = 2;
int osszeg = 1;
while (oszto * oszto < szam) {
if (szam % oszto == 0) {
osszeg += oszto;
osszeg += szam / oszto;
}
oszto++;
}
return osszeg;
}

#define N1 10000
#define N2 100
#define N3 1000

int main() {
int i;
int tokeletes = 0;
int hianyos = 0;
int bovelkedo = 0;
int bovelkedo2 = 0;
for (i = 1; i <= N1; i++) {
if (osztokOsszege(i) == i) {
tokeletes++;
}
}

for (i = 1; i <= N2; i++) {
if (osztokOsszege(i) < i) {
hianyos++;
}
}

for (i = 1; i <= N3; i++) {
if (osztokOsszege(i) > i) {
bovelkedo++;
if (i % 6 == 0) {
bovelkedo2++;
}
}
}
printf("Tokeletes szamok 1 es %d kozott: %d\n", N1, tokeletes);
printf("Hianyos szamok 1 es %d kozott: %d\n", N2, hianyos);
printf("Bovelkedo szamok 1 es %d kozott: %d\n", N3, bovelkedo);
printf("2-vel es 3-al oszthato bovelkedo szamok 1 es %d kozott:
%d\n", N3, bovelkedo2);
return EXIT_SUCCESS;
}
158 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.1.1.
#include <stdio.h>
int main() {
const int size=6;
int idxI;
char string[size+1]; // +1 for ending 0
printf("string=");
scanf("%6s", string);
printf("The string is: %s\n", string);
printf("The static string address, string: %p\n", string);
printf("The dynamic string address, &string: %p\n", &string);
for (idxI=0; idxI<size; idxI++) {
printf("\'%c\' ", string[idxI]);
}
printf("\n");
for (idxI=0; idxI<size; idxI++) {
if (string[idxI]==0) printf("0x");
printf("%#-2x ", string[idxI]);
}
printf("\n");
for (idxI=0; idxI<size; idxI++) {
printf("string[%d] ", idxI);
}
printf("\n");
for (idxI=0; idxI<size; idxI++) {
printf("%p ", &(string[idxI]));
}
return 0;
}
3.1.2.
#include <stdio.h>
int main() {
const int size = 6;
int idxI;
char string[size + 1]; // +1 for ending 0

printf("string=");
scanf("%6s", string);
printf("The string is: %s\n", string);
printf("The static string address, string: %p\n", string);
printf("The dynamic string address, &string: %p\n", &string);
for (idxI = 0; idxI < size; idxI++) {
printf("\'%c\'", string[idxI]);
if (string[idxI] == 0) {
printf("\t0x");
printf("%#-2x", string[idxI]);
} else {
printf("\t%#-2x", string[idxI]);
}
printf("\tstring[%d] ", idxI);
printf("\t%p ", &(string[idxI]));
printf("\n");
}
return 0;
}
3.2.1.
#include <stdio.h>
9. Megoldsok 159
Heckl Istvn, PE www.tankonyvtar.hu
#include <math.h>
int main() {
const int size=4;
int idxI, op1[size]={2, -3, 0, 1},
op2[size]={4, 2, -4, 5}, points=0, answer, result;
for (idxI=0; idxI<size; idxI++) {
printf("%d/%d=", op1[idxI], op2[idxI]);
scanf("%d", &answer);
result=op1[idxI]/op2[idxI];
printf("%d/%d=%d\n", op1[idxI], op2[idxI], result);
if (answer==result) {
points++;
}
printf("%d%%%d=", op1[idxI], op2[idxI]);
scanf("%d", &answer);
result=op1[idxI]%op2[idxI];

printf("%d%%%d=%d\n\n", op1[idxI], op2[idxI], result);
if (answer==result) {
points++;
}
}
printf("You have %d points.\n", points);
return 0;
}
3.2.2.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int A,B,TIP;
double result;

srand(time(NULL));
A=((rand() % 20));
B=((rand() % 20));
TIP=(rand() % 2);
if(!TIP){
result=A/B;
printf("Integer division:\n");
printf("%d/%d=%d\n",A,B,(int)result);
}else{
result=(double)A/(double)B;
printf("Floating point division:\n");
printf("%d/%d=%.4lf\n",A,B,result);
}
return 0;
}
3.3.1.
#include <stdio.h>
int main() {
char string[]="23 35678 1.2345e11 -9.8765432e-11";
short int shortIntValue;
int intValue;
float floatValue;
double doubleValue, sum;
160 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

sscanf(string, "%hd %d %f %lf", &shortIntValue, &intValue,
&floatValue, &doubleValue);
sum = shortIntValue + intValue + floatValue + doubleValue;
sprintf(string, "%lf", sum);
printf("The sum is %s", string);
return 0;
}
3.3.2.
#include <stdio.h>
int main() {
int idxI;
char string[] = "48.1658745 -654686835454.321635432435421 -
9.8765432e-11";
double doubleValue[3], sum = 0;

sscanf(string, "%lf %lf %lf", &doubleValue[0], &doubleValue[1],
&doubleValue[2]);
for (idxI = 0; idxI < 3; idxI++) {
doubleValue[idxI] = doubleValue[idxI] +idxI +1;
sum += doubleValue[idxI];
}
sprintf(string, "%+.8lf %+.8lf %+.8lf", doubleValue[0],
doubleValue[1], doubleValue[2]);
printf("The new string array is %s\n", string);
return 0;
}
3.4.1.
#include <stdio.h>
#include <conio.h>
int main() {
char string1[100], string2[100], string3[100];
int c, idxI;

printf("String input with getchar. Press enter, ctrl+z and enter to
end input!\n");
idxI=0;
while((c=getchar()) != EOF) {
string1[idxI]=c;
idxI++;
}
string1[--idxI]=0;
printf("String input with gets: ");
gets(string2);
printf("String input with scanf: ");
scanf(%s, string3);
printf("\nstring1 with getchar = %s\n", string1);
printf("string2 with gets = %s\n", string2);
printf("string3 with scanf = %s\n", string3);
printf("Press any key to exit!");
c=getch();
return 0;
}
9. Megoldsok 161
Heckl Istvn, PE www.tankonyvtar.hu
3.4.2.
A scanf a bufferben hagyja az entert gy a gets nem ll meg,
hanem az res sort veszi t a verembl. Egy plusz getchar a scanf
eltt kiveszi az entert a bufferbl.
3.5.1
#include <stdio.h>
#include <math.h>
int main() {
float tomb[5];
int idxI;

for (idxI=0; idxI<5; idxI++) {
tomb[idxI]=sqrt(idxI);
}
for (idxI=0; idxI<5; idxI++) {
printf("%f, ", tomb[idxI]);
}
return 0;
}
3.5.2.
#include <stdio.h>
#include <math.h>
int main() {
float * tomb;
int idxI, size;

printf("Size of array? ");
scanf("%d", &size);
tomb = (float*) malloc(size*sizeof(float));
for (idxI = 0; idxI < size; idxI++) //tomb feltoltese
tomb[idxI] = sqrt(idxI);
for (idxI = 0; idxI < size; idxI++) { //tomb kiiratasa
printf("%f", tomb[idxI]);
if(idxI+1 != size)
printf(",");
else
printf("\n");
}
free(tomb);
return 0;
}
3.6.1.
#include <stdio.h>
#include <math.h>
int main() {
const int size=4;
int tomb[size];
int idxI, idxJ;

for (idxI=0; idxI<size; idxI++) {
printf("The %d. value: ", idxI);
scanf("%d", &tomb[idxI]);
}
printf("\n%20.20s", " ");
for (idxI=0; idxI<size; idxI++) {
162 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
for (idxJ=0; idxJ<12; idxJ++) {
printf("*");
}
printf("");
}
printf("\n%20.20s", " ");
for (idxI=0; idxI<size; idxI++) {
printf("*%10d* ", tomb[idxI]);
}
printf("\n%20.20s", " ");
for (idxI=0; idxI<size; idxI++) {
for (idxJ=0; idxJ<12; idxJ++) {
printf("*");
}
printf("");
}
printf("\n%20.20s", "index: ");
for (idxI=0; idxI<size; idxI++) {
printf("%-13d", idxI);
}
printf("\n%20.20s", "address: ");
for (idxI=0; idxI<size; idxI++) {
printf("%-#13p", &tomb[idxI]);
}
printf("\n%20.20s%#p", "tomb: ", tomb);
printf("\n%20.20s%#p", &tomb: ", &tomb);
printf("\n%20.20s%d", "tomb size: ", size);
return 0;
}
3.6.2.
A dinamikus tmb mint mutat s az cme nem egyezik meg.
3.7.1.
#include <stdio.h>
#include <float.h>
int main() {
const int xSize=10, ySize=10;
float matrix[xSize][ySize]={
{4, 5, 6, 4, 2, 3, 4, 2, 4, 2},
{2, 2, 6, 5, 8, 7, 5, 3, 4, 2},
{4, 3, 6, 2, 6, 3, 4, 6, 7, 2},
{7, 2, 6, -2, -3, -3, -4, 6, 1, 2},
{4, 1, 6, -7, -2, -3, -2, -8, 4, 2},
{8, 1, 6, -7, -4, -3, -7, -6, -4, -2},
{4, 3, 6, 7, 3, -3, -4, -8, -2, -2},
{9, 2, 6, 6, 2, 2, -4, -8, -4, 2},
{4, 3, 6, 8, 3, 2, 4, -6, 4, 2},
{3, 3, 6, 7, 1, 3, 5, 6, 4, 2}};
int water, land, biggestIndexX, biggestIndexY, biggestWaterIndexX,
biggestWaterIndexY, idxI, idxJ;
float mostShallowWater, sum, avg;

water=0;
land=0;
for (idxI=0; idxI<xSize; idxI++) {
for (idxJ=0; idxJ<ySize; idxJ++) {
if (matrix[idxI][idxJ]>0) land++;
else water++;
9. Megoldsok 163
Heckl Istvn, PE www.tankonyvtar.hu
}
}
printf("The ration to land to water is = %d:%d\n", land, water);

biggestIndexX=0;
biggestIndexY=0;
for (idxI=0; idxI<xSize; idxI++) {
for (idxJ=0; idxJ<ySize; idxJ++) {
if (matrix[idxI][idxJ] > matrix[biggestIndexX][biggestIndexY])
{
biggestIndexX=idxI;
biggestIndexY=idxJ;
}
}
}
printf("The heighest point is at row: %d, column: %d and its height
is: %f\n", biggestIndexX, biggestIndexY,
matrix[biggestIndexX][biggestIndexY]);

// conditional optimum search
biggestWaterIndexX=-1;
biggestWaterIndexY=-1;
mostShallowWater=-FLT_MAX;
for (idxI=0; idxI<xSize; idxI++) {
for (idxJ=0; idxJ<ySize; idxJ++) {
if (matrix[idxI][idxJ] < 0 && matrix[idxI][idxJ] >
mostShallowWater) {
biggestWaterIndexX=idxI;
biggestWaterIndexY=idxJ;

mostShallowWater=matrix[biggestWaterIndexX][biggestWaterIndexY];
}
}
}
if (biggestWaterIndexX == -1) {
printf("There is no water so the search is meaningless.\n");
} else {
printf("The most shallow water is at row: %d, column: %d and its
depth is: %f\n", biggestWaterIndexX, biggestWaterIndexY,
mostShallowWater);
}

sum=0;
for (idxI=0; idxI<xSize; idxI++) {
for (idxJ=0; idxJ<ySize; idxJ++) {
sum+=matrix[idxI][idxJ];
}
}
avg=sum /(xSize*ySize);
printf("The average height is: %f\n", avg);

return 0;
}
3.7.2.
#include <stdio.h>
#include <float.h>
int main() {
const int xSize = 10, ySize = 10;
164 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
float matrix[10][10] = {
{4, 5, 6, 4, 2, 3, 4, 2, 4, 2},
{2, 2, 6, 5, 8, 7, 5, 3, 4, 2},
{4, 3, 6, 2, 6, 3, 4, 6, 7, 2},
{7, 2, 6, -2, -3, -3, -4, 6, 1, 2},
{4, 1, 6, -7, -2, -3, -2, -8, 4, 2},
{8, 1, 6, -7, -4, -3, -7, -6, -4, -2},
{4, 3, 6, 7, 3, -3, -4, -8, -2, -2},
{9, 2, 6, 6, 2, 2, -4, -8, -4, 2},
{4, 3, 6, 8, 3, 2, 4, -6, 4, 2},
{3, 3, 6, 7, 1, 3, 5, 6, 4, 2}
};
int biggestWaterIndexX, biggestWaterIndexY, lowestWaterIndexX,
lowestWaterIndexY;
int biggestLandIndexX, biggestLandIndexY, lowestLandIndexX,
lowestLandIndexY;
int idxI, idxJ;
float highestLand=-1, lowestLand=-1, deepestWater = 1,
shallowestWater = 1;

for (idxI=0; idxI<xSize && highestLand == -1; idxI++) {
//meghatarozzuk, hogy van-e fold
for (idxJ=0; idxJ<ySize && highestLand == -1; idxJ++) {
if (matrix[idxI][idxJ]>0)
highestLand = lowestLand = matrix[idxI][idxJ];
}
}
for (idxI=0; idxI<xSize && deepestWater == 1; idxI++) {
//meghatarozzuk, hogy van-e tenger
for (idxJ=0; idxJ<ySize && deepestWater == 1; idxJ++) {
if (matrix[idxI][idxJ]<=0)
deepestWater = shallowestWater = matrix[idxI][idxJ];
}
}
//foldon es vizen a legnagyobb es legkisebb ertekek meghatarozasa
for (idxI = 0; idxI < xSize; idxI++) {
for (idxJ = 0; idxJ < ySize; idxJ++) {
if (matrix[idxI][idxJ] > 0) {
if (matrix[idxI][idxJ] > highestLand)
highestLand = matrix[idxI][idxJ];
else if (matrix[idxI][idxJ] < lowestLand)
lowestLand = matrix[idxI][idxJ];
}
else {
if (matrix[idxI][idxJ] < deepestWater)
deepestWater = matrix[idxI][idxJ];
else if (matrix[idxI][idxJ] > shallowestWater)
shallowestWater = matrix[idxI][idxJ];
}
}
}
if(highestLand != -1)
printf("The level difference on land is %f\n", highestLand -
lowestLand);
if (deepestWater != 1)
printf("The level difference in water is %f\n", shallowestWater -
deepestWater);
if (highestLand != -1 && deepestWater != 1)
9. Megoldsok 165
Heckl Istvn, PE www.tankonyvtar.hu
printf("The biggest global level difference is %f\n", highestLand
- deepestWater);
else
printf("There's no global level difference!\n");
return 0;
}
3.8.1.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int repeatRequired, repeatAct, num, trial, idxI;
int frequency[6]={0};

printf("How much consecutive 6 do you want: ");
scanf("%d", &repeatRequired);
srand((unsigned)time(NULL));
repeatAct=0;
trial=0;
while (repeatAct!=repeatRequired) {
num = (rand()%6)+1;
frequency[num-1]++;
if (num==6) repeatAct++;
else repeatAct=0;
trial++;
}
printf("It needed %d random number to generate %d consecutive
6.\n\n", trial, repeatRequired);
printf("Meanwhile we generated\n");
for (idxI=0; idxI<6; idxI++)
printf("%d pieces of %d\n", frequency[idxI], idxI+1);
// repeatRequired=11, 100 millio trial, 2 s (2006)
return 0;
}
3.8.2.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int repeatRequired, repeatAct, num, trial, idxI;
int frequency[6] = {0}, sequence[30];
long int sum = 0;

printf("How much consecutive 6 do you want: ");
scanf("%d", &repeatRequired);
srand((unsigned)time(NULL));

for (idxI = 0; idxI < 30; ++idxI) {
repeatAct = 0;
trial = 0;
while (repeatAct!=repeatRequired) {
num = (rand()%6) + 1;
if (num == 6) //ha hatos akkor szamolom hany db egymas utan 6-
os
repeatAct++;
else //ha valamelyik szam nem hatos, ujrakezdem a szamolast
166 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
repeatAct=0;
trial++;
}
sequence[idxI] = trial; //hany probalkozas kellett az 1. 2. 3...
ismetlesnel
}
for (idxI = 0; idxI < 30; ++idxI) {
sum += sequence[idxI];
}
printf("It's needed on average %d random number to generate %d
consecutive 6.\n\n", sum/30, repeatRequired);
return 0;
}
3.9.1.
#include <stdio.h>

void print(float a, float b, float c) {
printf("a=%f b=%f c=%f\n", a, b, c);
}
void shift(float* a, float* b, float* c, int cyclic) {
float temp;

temp = *c;
*c = *b;
*b = *a;
if (cyclic)
*a = temp;
else
*a = 0;
}

int main() {
float x1, x2, x3;

printf("Provide the next number: ");
scanf("%f", &x1);
printf("Provide the next number: ");
scanf("%f", &x2);
printf("Provide the next number: ");
scanf("%f", &x3);
printf("Original: ");
print(x1, x2, x3);
shift(&x1, &x2, &x3, 1);
printf("After cyclic shift: ");
print(x1, x2, x3);
shift(&x1, &x2, &x3, 0);
printf("After non-cyclic shift: ");
print(x1, x2, x3);
return 0;
}
3.9.2.
#include <stdio.h>

void print(float a[], int size) {
int i;
for(i = 0; i < size; ++i)
printf("a[%d]= %f ", i, a[i]);
9. Megoldsok 167
Heckl Istvn, PE www.tankonyvtar.hu
printf("\n");
}
void shift(float* a, int cyclic) {
float temp;

temp = a[2];
a[2] = a[1];
a[1] = a[0];
if (cyclic)
a[0] = temp;
else
a[0] = 0;
}

int main() {
float x[3];

printf("Provide the next number: ");
scanf("%f", &x[0]);
printf("Provide the next number: ");
scanf("%f", &x[1]);
printf("Provide the next number: ");
scanf("%f", &x[2]);
printf("Original: ");
print(x, 3);
shift(x, 1);
printf("After cyclic shift: ");
print(x, 3);
shift(x, 0);
printf("After non-cyclic shift: ");
print(x, 3);
return 0;
}
3.9.3.
#include <stdio.h>
#include <malloc.h>

void print(float a[], int size) {
int idxI;
for(idxI = 0; idxI < size; ++idxI)
printf("myArray[%d]= %f ", idxI, a[idxI]);
printf("\n");
}
void shift(float* a, char direction, int cyclic, int size) {
float temp = (direction=='r')?a[size-1]:a[0];
int idxI;
if(direction == 'r') { //ha jobbra shiftelunk
for(idxI = size-1; idxI > 0; --idxI) {
a[idxI] = a[idxI-1];
}
if (cyclic)
a[0] = temp;
else
a[0] = 0;
}
else { //ha balra shiftelunk
for(idxI = 0; idxI < size; ++idxI) {
a[idxI] = a[idxI+1];
168 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
if (cyclic)
a[size-1] = temp;
else
a[size-1] = 0;
}
}

int main() {
float *myArray;
int size, idxI;
char direction;

printf("Array size? "); scanf("%d", &size);
myArray = (float*) malloc(sizeof(float)*size);
for(idxI = 0; idxI < size; ++idxI) {
printf("Provide the next number: ");
scanf("%f", &myArray[idxI]);
}
_flushall();
printf(Original array: );
print(myArray, size);
printf("In which direction do you want to shift? (l/r) ");
scanf("%c", &direction);
_flushall();

printf("After cyclic shift: ");
shift(myArray, direction, 1, size);
print(myArray, size);

printf("After non-cyclic shift: ");
shift(myArray, direction, 0, size);
print(myArray, size);
return 0;
}
3.10.1
/* FILE INC_HPP_*/
#define INC_HPP_

void print(double*, int);
double sum(double*, int);
double avg(double*, int);
int minIndex(double*, int);
int searchFor(double*, int, double);

#endif


/* FILE INC_CPP_*/
#include <stdio.h>
#include "inc.hpp"

void print(double* tomb, int size) {
int idxI;
printf("[");
for (idxI=0; idxI<size; idxI++)
printf("%lf ", tomb[idxI]);
printf("]");
9. Megoldsok 169
Heckl Istvn, PE www.tankonyvtar.hu

}
double sum(double* tomb, int size) {
double result=0;
int idxI;
for (idxI=0; idxI<size; idxI++)
result += tomb[idxI];
return result;
}
double avg(double* tomb, int size) {
double result = sum(tomb, size) / size;
return result;
}
int minIndex(double* tomb, int size) {
int minIndex = 0;
int idxI;
for (idxI=1; idxI<size; idxI++)
if (tomb[idxI] < tomb[minIndex])
minIndex = idxI;
return minIndex;
}
int searchFor(double* tomb, int size, double data) {
int idxI;
for (idxI=1; idxI<size; idxI++)
if (tomb[idxI] == data)
return 1; // data found
return 0; // data is not found
}


/* FILE ARRAY_CPP_*/
#include <stdio.h>
#include "inc.hpp"

int main() {
double myArray[]={12, 56, -7}, mySum, myAvg;
int size = sizeof myArray / sizeof (double); // works only with
static arrays
double what=-8;

print(myArray, size);
mySum=sum(myArray, size);
myAvg=avg(myArray, size);
printf("\nThe sum of the array is: %lf, and the average is: %lf",
mySum, myAvg);
printf("\nThe minimum elem is: %lf", myArray[minIndex(myArray,
size)]);
if ( searchFor(myArray, size, what))
printf("\n%lf is found.", what);
else
printf("\n%lf is not found.", what);
return 0;
}
3.10.2.
#ifndef FUNCTION_H_
#define FUNCTION_H_

void print(double*, int);
170 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
double sum(double*, int);
double avg(double*, int);
int minIndex(double*, int);
int maxIndex(double*, int);
void change(double*, double*, int);
int searchFor(double*, int, double);

#endif /* FUNCTION_H_ */

/* FILE FUNCTION_C*/
#include <stdio.h>
#include "function.h"

void print(double* tomb, int size) {
int idxI;
printf("[");
for (idxI = 0; idxI < size; idxI++)
printf("%lf ", tomb[idxI]);
printf("]");

}
double sum(double* tomb, int size) {
double result = 0;
int idxI;
for (idxI = 0; idxI < size; idxI++)
result += tomb[idxI];
return result;
}
double avg(double* tomb, int size) {
double result = sum(tomb, size) / size;
return result;
}
int minIndex(double* tomb, int size) {
int minIndex = 0;
int idxI;
for (idxI = 1; idxI < size; idxI++)
if (tomb[idxI] < tomb[minIndex])
minIndex = idxI;
return minIndex;
}

int maxIndex(double* tomb, int size) {
int maxIndex = 0;
int idxI;
for (idxI = 1; idxI < size; idxI++)
if (tomb[idxI] > tomb[maxIndex])
maxIndex = idxI;
return maxIndex;
}

void change(double* tomb, double* tomb2, int size) {
double helper;
int idxI;
for (idxI = 0; idxI < size; idxI++) {
helper = tomb[idxI];
tomb[idxI] = tomb2[idxI];
tomb2[idxI] = helper;
}

9. Megoldsok 171
Heckl Istvn, PE www.tankonyvtar.hu
}

int searchFor(double* tomb, int size, double data) {
int idxI;
for (idxI = 1; idxI < size; idxI++)
if (tomb[idxI] == data)
return 1; // data found
return 0; // data is not found
}


/* FILE 2_35_2_C*/
#include <stdio.h>
#include "function.h"

int main() {
double myArray[] = { 12, 56, -7 }, myArray2[] = { 24, -26, 4 },
mySum, myAvg;
int size = sizeof myArray / sizeof(double); // works only with static
arrays
double what = -8;

print(myArray, size);
mySum = sum(myArray, size);
myAvg = avg(myArray, size);
printf("\nThe sum of the array is: %lf, and the average is: %lf",
mySum,
myAvg);
printf("\nThe minimum elem is: %lf", myArray[minIndex(myArray,
size)]);
printf("\nThe maximum elem index is: %d", maxIndex(myArray, size));
printf("\nThe old array:\nA: ");
print(myArray, size);
printf("\nB: ");
print(myArray2, size);
change(myArray, myArray2, size);
printf("\nThe new array:\nA: ");
print(myArray, size);
printf("\nB:");
print(myArray2, size);
if (searchFor(myArray, size, what))
printf("\n%lf is found.", what);
else
printf("\n%lf is not found. ", what);
return 0;
}
3.10.3.
#ifndef FUNCTION_H_
#define FUNCTION_H_

void print(double*, int);
double sum(double*, int);
double avg(double*, int);
int minIndex(double*, int);
int maxIndex(double*, int);
void change(double*, double*, int);
void alapmuvelet(double*, double*, int);
double skalaris(double*, double*, int);
172 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int elsoElofordulas(double*, int, double);
int utolsoElofordulas(double*, int, double);
int searchFor(double*, int, double);

#endif /* FUNCTION_H_ */

/* FILE FUNCTION_C*/
#include <stdio.h>
#include "function.h"

void print(double* tomb, int size) {
int idxI;
printf("[");
for (idxI = 0; idxI < size; idxI++)
printf("%lf ", tomb[idxI]);
printf("]");

}
double sum(double* tomb, int size) {
double result = 0;
int idxI;
for (idxI = 0; idxI < size; idxI++)
result += tomb[idxI];
return result;
}
double avg(double* tomb, int size) {
double result = sum(tomb, size) / size;
return result;
}
int minIndex(double* tomb, int size) {
int minIndex = 0;
int idxI;
for (idxI = 1; idxI < size; idxI++)
if (tomb[idxI] < tomb[minIndex])
minIndex = idxI;
return minIndex;
}
int maxIndex(double* tomb, int size) {
int maxIndex = 0;
int idxI;
for (idxI = 1; idxI < size; idxI++)
if (tomb[idxI] > tomb[maxIndex])
maxIndex = idxI;
return maxIndex;
}
void change(double* tomb, double* tomb2, int size) {
double helper;
int idxI;
for (idxI = 0; idxI < size; idxI++) {
helper = tomb[idxI];
tomb[idxI] = tomb2[idxI];
tomb2[idxI] = helper;
}

}
void alapmuvelet(double* tomb, double*tomb2, int size) {
int idxI;
for (idxI = 0; idxI < size; idxI++) {
printf("\n%d.", idxI);
9. Megoldsok 173
Heckl Istvn, PE www.tankonyvtar.hu
printf("\n%lf + %lf = %lf", tomb[idxI], tomb2[idxI], tomb[idxI]
+ tomb2[idxI]);
printf("\n%lf - %lf = %lf", tomb[idxI], tomb2[idxI], tomb[idxI]
- tomb2[idxI]);
printf("\n%lf * %lf = %lf", tomb[idxI], tomb2[idxI], tomb[idxI]
* tomb2[idxI]);
printf("\n%lf / %lf = %lf", tomb[idxI], tomb2[idxI], tomb[idxI]
/ tomb2[idxI]);
}
}
double skalaris(double* tomb, double*tomb2, int size) {
double skalar = 0;
int idxI;
for (idxI = 0; idxI < size; idxI++) {
skalar += tomb[idxI] * tomb2[idxI];
}
return skalar;
}
int elsoElofordulas(double* tomb, int size, double data) {
int index = -1;
int idxI;
for (idxI = 0; idxI < size; idxI++) {
if ((index == -1) && (data == tomb[idxI])) {
index = idxI;
}
}
return index;
}
int utolsoElofordulas(double* tomb, int size, double data) {
int index = 0;
int idxI;
for (idxI = 0; idxI < size; idxI++) {
if (data == tomb[idxI]) {
index = idxI;
}
}
return index;
}
int searchFor(double* tomb, int size, double data) {
int idxI;
for (idxI = 1; idxI < size; idxI++)
if (tomb[idxI] == data)
return 1; // data found
return 0; // data is not found
}

/* FILE 2_35_3_C*/
#include <stdio.h>
#include "function.h"

int main() {
double myArray[] = { 12, 56, -7, 56 }, myArray2[] = { 24, -26, 4, 19
},
mySum, myAvg;
int size = sizeof myArray / sizeof(double), elsoindex, utolsoindex;
// works only with static arrays
double what = -8, what2 = 56;

print(myArray, size);
174 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
mySum = sum(myArray, size);
myAvg = avg(myArray, size);
printf("\nThe sum of the array is: %lf, and the average is: %lf",
mySum,
myAvg);
printf("\nThe minimum elem is: %lf", myArray[minIndex(myArray,
size)]);
printf("\nThe maximum elem index is: %d", maxIndex(myArray, size));
if (searchFor(myArray, size, what))
printf("\n%lf is found.", what);
else
printf("\n%lf is not found.", what);
printf("\nThe old array:\nA:");
print(myArray, size);
printf("\nB:");
print(myArray2, size);
change(myArray, myArray2, size);
printf("\nThe new array:\nA:");
print(myArray, size);
printf("\nB:");
print(myArray2, size);
alapmuvelet(myArray, myArray2, size);
printf("\nSkalris szorzat: %lf", skalaris(myArray, myArray2, size));
elsoindex = elsoElofordulas(myArray2, size, what2);
utolsoindex = utolsoElofordulas(myArray2, size, what2);
if (elsoindex != -1) {
printf("\n%lf elso elofordulas indexe: %d", what2, elsoindex);
printf("\n%lf utolso elofordulas indexe: %d", what2, utolsoindex);
} else {
printf("\n%lf nem talalhato! ", what2);
}
return 0;
}
3.11.1.
#include <stdio.h>
#include <string.h>

int devisableBy4(int num) {
if (num/4==num/4.)
return 1;
return 0;
}

int main() {
char s[]="The project will scale up to 1,200 marine sites,\n"
"including different conditions such as surface waters,\n"
"waters near methane emissions from the sea floor, and deep-sea
sediments. ";

int idxI, size;
size = strlen(s);
for (idxI=0; idxI<size; idxI++) {
if (!devisableBy4(idxI) || (s[idxI]=='\n' || s[idxI]=='\t' ||
s[idxI]==' '))
printf("%c", s[idxI]);
}
return 0;
}
9. Megoldsok 175
Heckl Istvn, PE www.tankonyvtar.hu
3.11.2.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char string[] = "The project will scale up to 1,200 marine sites,\n"
"including different conditions such as surface waters,\n"
"waters near methane emissions from the sea floor, and deep-
seasediments.";
int idxI, size;
size = strlen(string);

for (idxI = 0; idxI < size; idxI++) {
if ( (toupper(string[idxI]) == 'A' || toupper(string[idxI]) == 'E'
|| toupper(string[idxI]) == 'I' || toupper(string[idxI]) == 'O' ||
toupper(string[idxI])== 'U') && string[idxI - 1] != ' ')
; //ha maganhazo, es elotte nem szokoz van, tehat nem
keudobetu, akkor nem csinal semmit
else
printf("%c", string[idxI]);
}
return 0;
}
3.12.1.
#include <stdio.h>
#include <string.h>
int main() {
char sz[80];
char c;
int n, a, o, i, e, u, idxI;
printf("text=\n");
gets(sz);
n = strlen(sz);
a = o = i = e = u = 0;
for(idxI = 0; idxI < n; idxI++) {
c = sz[idxI];
switch (c) {
case 'a':
case 'A':
a++;
break;
case 'o':
case 'O':
o++;
break;
case 'i':
case 'I':
i++;
break;
case 'e':
case 'E':
e++;
break;
case 'u':
case 'U':
u++;
break;
}
176 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
printf("Vowel statistics:\n");
printf(" a,A: %d\n", a);
printf(" e,E: %d\n", e);
printf(" i,I: %d\n", i);
printf(" o,O: %d\n", o);
printf(" u,U: %d\n", u);
return 0;
}
3.12.2.
#include <stdio.h>
#include <string.h>
int main() {
char text[80];
char nextChar;
int textSize, sentence, word, idxI;

printf("Text= ");
gets(text);
textSize = strlen(text);
if (text[0] == '\0')
sentence = word = 0;
else {
sentence = 0;
word = 1;
}
for (idxI = 0; idxI < textSize; idxI++) {
nextChar = text[idxI];
switch (nextChar) {
case ' ':
word++;
break;
case '.':
case '!':
case '?':
sentence++;
break;
}
}
printf("Vowel statistics:\n");
printf("Word: %d\n", word);
printf("Sentence: %d\n", sentence);
return 0;
}

3.13.1.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int in(char c) {
char s[]="AEIOU";
unsigned int idxI;
idxI=0;
do {
if (c == s[idxI]) return 1;
idxI++;
} while (idxI <= strlen(s));
9. Megoldsok 177
Heckl Istvn, PE www.tankonyvtar.hu
return 0;
}
int main() {
char orig[255], newVer[255], kar;
unsigned int idxI;
int idxJ;
printf("sentence=\n");
gets(orig);
idxJ=-1;
for(idxI=0; idxI<strlen(orig); idxI++) {
idxJ++;
kar=toupper(orig[idxI]);
newVer[idxJ]=kar;
if( in(kar) ) {
newVer[++idxJ]='V';
newVer[++idxJ]=kar;
}
}
newVer[++idxJ]='\0';
printf("%s", newVer);
return 0;
}
3.13.2.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
int main() {
char original[255], *newVer;
int idxI, idxJ;

printf("Sentence: ");
gets(original);
newVer = (char*) malloc (sizeof(char)*strlen(original)); //dinamikus
foglalas
idxJ = 0;
for (idxI = 0; idxI < strlen(original); idxI++) {
if (toupper(original[idxI]) != 'V') {
newVer[idxJ] = toupper(original[idxI]);
idxJ++;
}
else { //ha v betut talalok
if ( toupper(original[idxI]) == toupper(original[idxI + 2]) )
{ //ha egymas utan ket v; vivi->vi
newVer[idxJ++] = toupper(original[idxI++]);
newVer[idxJ++] = toupper(original[idxI++]);
idxI++;
}
else
idxI++;
}
}
newVer[idxJ] = '\0';
printf("%s\n", newVer);
free(newVer);
return 0;
}
178 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.14.1.
#include <stdio.h>
#include <string.h>
void substract(char* from, char* what) {
char* subString=0;
int len;

subString=strstr(from, what);
if (!subString) return;
len = strlen(what);
strcpy(subString, subString+len); // almafavirag -> almavirag\0g
}
int main() {
char from[200], what[100];

printf("Substract from=");
scanf("%s", from);
printf("Substract what=");
scanf("%s", what);
substract(from, what);
printf("\nThe reduced word is: %s", from);
return 0;
}
3.14.2.
#include <stdio.h>
#include <string.h>
void substract(char* from, char* what) {
char* subString = 0;
int length;
subString = strstr(from, what);
if (!subString)
return;
length = strlen(what);
strcpy(subString, subString + length); // almafavirag -> almavirag\0g
substract(from, what);
}
int main() {
char from[200], what[100];

printf("Substract from=");
scanf("%s", from);
printf("Substract what=");
scanf("%s", what);
substract(from, what);
printf("\nThe reduced word is: %s\n", from);
return 0;

}
3.15.1.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>

char* upperCase(char* string) {
char* result=0;
int len, idxI;
9. Megoldsok 179
Heckl Istvn, PE www.tankonyvtar.hu

result = strdup(string);
len = strlen(string);
for (idxI=0; idxI<len; idxI++)
result[idxI]=toupper(result[idxI]);
return result;
}
char* lowerCase(char* string) {
char* result=0;
int len, idxI;

result = strdup(string);
len = strlen(string);
for (idxI=0; idxI<len; idxI++)
result[idxI]=tolower(result[idxI]);
return result;
}
char* toggleCase(char* string) {
char* result=0;
int len, idxI;

result = strdup(string);
len = strlen(string);
for (idxI=0; idxI<len; idxI++) {
if (isupper(result[idxI]))
result[idxI]=tolower(result[idxI]);
else
result[idxI]=toupper(result[idxI]);
}
return result;
}
char* sentenceCase(char* string) {
char* result=0;
int len, idxI;

result = strdup(string);
len = strlen(string);
result[0]=toupper(result[0]);
for (idxI=1; idxI<len; idxI++)
result[idxI]=tolower(result[idxI]);
return result;
}
char* titleCase(char* string) {
char* result=0;
int len, idxI, startWord=1;

result = strdup(string);
len = strlen(string);
for (idxI=0; idxI<len; idxI++) {
if (startWord)
result[idxI]=toupper(result[idxI]);
else
result[idxI]=tolower(result[idxI]);
if (result[idxI]==' ')
startWord = 1;
else
startWord = 0;
}
return result;
180 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
int menu() {
int select;
printf("UPPER CASE - 1\n");
printf("lower case - 2\n");
printf("tOGGLE CASE - 3\n");
printf("Sentence case - 4\n");
printf("Title Case - 5\n");
scanf("%d", &select);
return select;
}
int main() {
char myString[200], *result;
int cheoice;
printf("orinigal string=");
gets(myString);
choice = menu();
switch (choice) {
case 1:
result = upperCase(myString);
break;
case 2:
result = lowerCase(myString);
break;
case 3:
result = toggleCase(myString);
break;
case 4:
result = sentenceCase(myString);
break;
case 5:
result = titleCase(myString);
break;
}
printf("\nresult=\"%s\"", result);
free(result);
return 0;
}
3.15.2.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>

char* lowerCase(char* string) {
char* result=0;
int len, idxI;

result = _strdup(string);
len = strlen(string);
for (idxI = 0; idxI < len; idxI++)
result[idxI] = tolower(result[idxI]);
return result;
}
char* sentenceCase(char* string) {
char* result = 0;
int len, idxI;

9. Megoldsok 181
Heckl Istvn, PE www.tankonyvtar.hu
result = _strdup(string);
len = strlen(string);
result[0] = toupper(result[0]);
for (idxI = 1; idxI < len; idxI++)
result[idxI] = tolower(result[idxI]);
return result;
}
char* niceTitleCase(char* string) {
char* result = 0;
int len, idxI, startWord = 1;
result = _strdup(string);
len = strlen(string);

result = lowerCase(result); //elosszor minden betu legyen kicsi
result = sentenceCase(result); //a mondat kezdodjon nagybetuvel
for (idxI = 0; idxI < len; idxI++) {
if (result[idxI] == ':') { //ha :-ot talalunk a kovetkezo betu
legyen mindenfele keppen nagybetu
result[idxI+1] = toupper(result[idxI+1]);
idxI++;
}
//for, and, the, from, of, in... szavak maradjanak kisbetusek
else if( result[idxI] == 'f' && result[idxI+1] == 'o' &&
result[idxI+2] == 'r' && result[idxI+3] == ' ')
idxI += 3;
else if (result[idxI] == 'a' && result[idxI+1] == 'n' &&
result[idxI+2] == 'd' && result[idxI+3] == ' ')
idxI += 3;
else if (result[idxI] == 't' && result[idxI+1] == 'h' &&
result[idxI+2] == 'e' && result[idxI+3] == ' ')
idxI += 3;
else if (result[idxI] == 'f' && result[idxI+1] == 'r' &&
result[idxI+2] == 'o' && result[idxI+3] == 'm' && result[idxI+4] == ' ')
idxI += 4;
else if (result[idxI] == 'o' && result[idxI+1] == 'f' &&
result[idxI+2] == ' ')
idxI += 2;
else if (result[idxI] == 'i' && result[idxI+1] == 'n' &&
result[idxI+2] == ' ')
idxI += 2;
//egyebkent minden szo kezdodjon nagybetuvel
else if (startWord)
result[idxI] = toupper(result[idxI]);
else
result[idxI] = tolower(result[idxI]);
if (result[idxI] == ' ' || result[idxI] == '\t' || result[idxI] ==
'\n')
startWord = 1;
else
startWord = 0;
}
return result;
}
int main() {
char myString[200], *result;
printf("original string=");
gets(myString);

result = niceTitleCase(myString);
182 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

printf("\nresult= \"%s\"\n", result);
free(result);
return 0;
}
3.16.1.
#include <malloc.h>
#include <memory.h>

int main() {
int size, idxI;
double *array=NULL, *temp=NULL;

printf("array size: ");
scanf("%d", &size);
array = (double*)malloc(size*sizeof(double));
for (idxI=0; idxI<size; idxI++) {
printf("%d. element: ", idxI);
scanf("%lf", &array[idxI]);
}
temp = (double*)malloc(size*2*sizeof(double));
memcpy(temp, array, size*sizeof(double));
array = temp;
size *= 2;
temp = NULL; // free is not needed here
for (idxI=size/2; idxI<size; idxI++) {
printf("%d. element: ", idxI);
scanf("%lf", &array[idxI]);
}
free(array);
array = NULL;
return 0;
}
3.16.2.
#include <stdio.h>
#include <malloc.h>
#include <memory.h>
double* allocArray(int* size) {
// version: 1 of 4
double* result=NULL;
printf("\narray size: ");
scanf("%d", size);
result = (double*)malloc(*size * sizeof(double));
return result;
}
int main() {
int size, idxI;
double *array=NULL, *temp=NULL;

array = allocArray(&size);
for (idxI=0; idxI<size; idxI++) {
printf("%d. element: ", idxI);
scanf("%lf", &array[idxI]);
}
temp = (double*)malloc(size*2*sizeof(double));
memcpy(temp, array, size*sizeof(double));
array = temp;
9. Megoldsok 183
Heckl Istvn, PE www.tankonyvtar.hu
size *= 2;
temp = NULL; // free is not needed here
for (idxI=size/2; idxI<size; idxI++) {
printf("%d. element: ", idxI);
scanf("%lf", &array[idxI]);
}
free(array);
array = NULL;
return 0;
}
3.17.1.
#include <stdio.h>
#include <malloc.h>
#include <memory.h>
#include <time.h>

double** allocMatrix(int rows, int cols) {
double** result=NULL;
int idxI;
if (rows<=0 || cols<=0)
return NULL;
result = (double**)malloc(rows * sizeof(double*));
for (idxI=0; idxI<rows; idxI++) {
result[idxI] = (double*)malloc(cols * sizeof(double));
}
return result;
}

void freeMatrix(double** mat, int rows) {
int idxI;
if (rows<=0)
return;
if (!mat)
return;
for (idxI=0; idxI<rows; idxI++) {
if (!mat[idxI])
free(mat[idxI]);
}
free(mat);
}

void randMatrix(double** mat, int rows, int cols, int min, int max) {
int idxI, idxJ;
if (rows<=0 || cols<=0)
return;
srand((unsigned int)time(NULL));
for (idxI=0; idxI<rows; idxI++) {
for (idxJ=0; idxJ<cols; idxJ++) {
mat[idxI][idxJ] = rand()%(max-min+1)+min;
}
}
}

double** multMatrix(double** matA, int rowA, int colA, double** matB, int
rowB, int colB, int *rowC, int *colC) {
double** result=NULL, sum;
int idxI, idxJ, idxK;
if (colA != rowB)
184 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
return NULL;
*rowC = rowA;
*colC = colB;
result = allocMatrix(*rowC, *colC);
srand((unsigned int)time(NULL));
for (idxI=0; idxI<rowA; idxI++) {
for (idxJ=0; idxJ<colB; idxJ++) {
sum = 0;
for (idxK=0; idxK<colA; idxK++) {
sum += matA[idxI][idxK]*matB[idxK][idxJ];
}
result[idxI][idxJ] = sum;
}
}
return result;
}

void printMatrix(double** mat, int rows, int cols) {
int idxI, idxJ;
if (rows<=0 || cols<=0)
return;
for (idxI=0; idxI<rows; idxI++) {
printf("[");
for (idxJ=0; idxJ<cols; idxJ++) {
printf("%lf, ", mat[idxI][idxJ]);
}
printf("]\n");
}
}

int main() {
int rowA, colA, rowB, colB, rowC, colC;
double **matA=NULL, **matB=NULL, **matC=NULL;

printf("Number of rows of matrix A: ");
scanf("%d", &rowA);
printf("Number of columns of matrix A: ");
scanf("%d", &colA);
printf("Number of rows of matrix B: ");
scanf("%d", &rowB);
printf("Number of columns of matrix B: ");
scanf("%d", &colB);

matA = allocMatrix(rowA, colA);
matB = allocMatrix(rowB, colB);
randMatrix(matA, rowA, colA, 12, 16);
randMatrix(matB, rowB, colB, -4, 5);
matC = multMatrix(matA, rowA, colA, matB, rowB, colB, &rowC, &colC);

printf("matrix A =\n");
printMatrix(matA, rowA, colA);
printf("matrix B =\n");
printMatrix(matB, rowB, colB);
printf("matrix A*B =\n");
printMatrix(matC, rowC, colC);

freeMatrix(matA, rowA); matA = NULL;
freeMatrix(matB, rowB); matB = NULL;
freeMatrix(matC, rowC); matC = NULL;
9. Megoldsok 185
Heckl Istvn, PE www.tankonyvtar.hu
return 0;
}
3.17.2.
#include <stdio.h>
#include <malloc.h>
#include <memory.h>
#include <time.h>

double** allocMatrix(int rows, int cols) {
double** result = NULL;
int idxI;
if (rows <= 0 || cols <= 0)
return NULL;
result = (double**) malloc(rows * sizeof(double*));
for (idxI = 0; idxI < rows; idxI++) {
result[idxI] = (double*) malloc(cols * sizeof(double));
}
return result;
}

void freeMatrix(double** mat, int rows) {
int idxI;
if (rows <= 0)
return;
if (!mat)
return;
for (idxI = 0; idxI < rows; idxI++) {
free(mat[idxI]);
}
free(mat);
}

void randMatrix(double** mat, int rows, int cols, int min, int max) {
int idxI, idxJ;
if (rows <= 0 || cols <= 0)
return;
srand((unsigned int) time(NULL));
for (idxI = 0; idxI < rows; idxI++) {
for (idxJ = 0; idxJ < cols; idxJ++) {
mat[idxI][idxJ] = rand() % (max - min + 1) + min;
}
}
}

void printMatrix(double** mat, int rows, int cols) {
int idxI, idxJ;

if (rows <= 0 || cols <= 0)
return;
for (idxI = 0; idxI < rows; idxI++) {
printf("[");
for (idxJ = 0; idxJ < cols; idxJ++) {
printf("%.2lf, ", mat[idxI][idxJ]);
}
printf("]\n");
}

}
186 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

void cutMatrix(double ** mat, int rows, int cols) {
double** result = NULL;
int selected, newcols = 0, newrows = 0, i, j, db = 0;
printf("1. Cut the bottom and add to the right side.\n");
printf("2. Cut the bottom\n");
printf("3. Add to the right side\n");
printf("Choose: ");
scanf("%d", &selected);
switch (selected) {
case 1:
printf("How many rows whould you like to delete? ");
scanf("%d", &newrows);
printf("How many columns whould you like to add to the right side?
");
scanf("%d", &newcols);
newcols += cols;
newrows = cols - newrows;
result = allocMatrix(newrows, newcols);
for (i = 0; i < newrows; i++) {
for (j = 0; j < newcols; j++) {
result[i][j] = mat[i][j];
}
}
for (i = 0; i < cols; i++) {
if ((i + 1) % (newrows) == 0) {
db++;
}
}

for (i = cols; i < newcols; i++) {
for (j = 0; j < newrows; j++) {
if ((((i + 1) - (newrows * db)) / (j + 1)) == 1 && (((i +
1)
- (newrows * db)) % (j + 1)) == 0) {
result[j][i] = 1;
} else {
result[j][i] = 0;
}
}
if ((i + 1) % (newrows) == 0) {
db++;
}
}
break;
break;
case 2:
printf("How many rows whould you like to delete? ");
scanf("%d", &newrows);
newcols += cols;
newrows = rows - newrows;
result = allocMatrix(newrows, newcols);
for (i = 0; i < newrows; i++) {
for (j = 0; j < newcols; j++) {
result[i][j] = mat[i][j];
}
}
break;
case 3:
9. Megoldsok 187
Heckl Istvn, PE www.tankonyvtar.hu
printf("How many columns whould you like to add to the right side?
");
scanf("%d", &newcols);
newcols += cols;
newrows += rows;
result = allocMatrix(newrows, newcols);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
result[i][j] = mat[i][j];
}
}
for (i = 0; i < cols; i++) {
if ((i + 1) % (newrows) == 0) {
db++;
}
}

for (i = cols; i < newcols; i++) {
for (j = 0; j < newrows; j++) {
if ((((i + 1) - (newrows * db)) / (j + 1)) == 1 && (((i +
1)
- (newrows * db)) % (j + 1)) == 0) {
result[j][i] = 1;
} else {
result[j][i] = 0;
}
}
if ((i + 1) % (newrows) == 0) {
db++;
}
}
break;
}
printf("matrix A =\n");
printMatrix(mat, rows, cols);
printf("new matrix A =\n");
printMatrix(result, newrows, newcols);
freeMatrix(result, newrows);
}

int main() {
int rowA, colA;
double **matA = NULL;

printf("Number of rows of matrix A: ");
scanf("%d", &rowA);
printf("Number of columns of matrix A: ");
scanf("%d", &colA);

matA = allocMatrix(rowA, colA);
randMatrix(matA, rowA, colA, 12, 16);

cutMatrix(matA, rowA, colA);

freeMatrix(matA, rowA);
matA = NULL;
return 0;
}
188 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
3.18.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const int limit=5;
typedef struct {
FILE* bf;
double* array;
long int size;
} Store;

void initStore(Store* myStore) {
printf("Size of the array: ");
scanf("%ld", &myStore->size);
if (myStore->size>limit)
myStore->bf = fopen("temp.txt", "w+b");
else
myStore->array = (double*)malloc(sizeof(double)*myStore->size);
return;
}

void delStore(Store* myStore) {
if (myStore->size>limit) {
fclose(myStore->bf); myStore->bf = NULL;
} else
free(myStore->array); myStore->array = NULL;
return;
}

void readStore(Store* myStore) {
double result;
int idx;
printf("Index of element to read: ");
scanf("%d", &idx);
if (myStore->size>limit) {
fseek(myStore->bf, sizeof(double)*idx, SEEK_SET);
fread(&result, sizeof(double), 1, myStore->bf);
} else {
result = myStore->array[idx];
}
printf("At %d there is: %lf\n", idx, result);
}

void writeStore(Store* myStore) {
double value;
int idx;
printf("Index of element to write: ");
scanf("%d", &idx);
printf("value: ");
scanf("%lf", &value);
if (myStore->size>limit) {
fseek(myStore->bf, sizeof(double)*idx, SEEK_SET);
fwrite(&value, sizeof(double), 1, myStore->bf);
// fflush(myStore->bf);
} else {
myStore->array[idx] = value;
}
9. Megoldsok 189
Heckl Istvn, PE www.tankonyvtar.hu
printf("%lf is written at %d\n", value, idx);
}

int main() {
Store myStore={NULL, NULL, 0};
int selection=0;

initStore(&myStore);
while (selection!=3) {
printf("\nRead - 1\nWrite - 2\nQuit - 3\n");
scanf("%d", &selection);
switch (selection) {
case 1:
readStore(&myStore);
break;
case 2:
writeStore(&myStore);
break;
}
}
delStore(&myStore);
return 0;
}
3.19.1.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main() {
char words[][50]={"element", "size", "love", "ball", "toy", "gambit",
"cruiser",
"shadow", "console", "Atlantis", "port", "staple", "Leonardo",
"bug",
"hope", "vanity", "time", "issue", "fan", "strength"};
char temp[50];
int size=sizeof(words)/sizeof(*words); // sizeof(*words) = 50
int trial, idxI, randIndex, errors=0;
clock_t start, finish;
double duration;

srand((unsigned)time(NULL));
printf("How much word would you like to type: ");
scanf("%d", &trial);
start = clock();
for (idxI=0; idxI<trial; idxI++) {
randIndex = rand() % size;
printf("type: %s\n", words[randIndex]);
scanf("%s", temp);
while (strcmp(temp, words[randIndex]) != 0) {
printf("error!\n");
errors++;
scanf("%s", temp);
}
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("Ellapsed time: %4.2lf\n", duration);
190 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("Number of good trials: %d, bad trials: %d", trial, errors);
return 0;
}
3.20.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INPUT_FILE "numbers.txt"
#define MAX_NUMBER_LENGTH 101
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))


char AddChar(char A, char B, char C)
{
int n = (A - '0') + (B - '0') + (C - '0');
return ( (n % 10)) + '0';
}

char AddM(char A, char B, char C)
{
int n = (A - '0') + (B - '0') + (C - '0');
return ( (n / 10)) + '0';
}

void Add(char * NA, char * NB, char * C)
{
char m;
int AI, BI;
char * A;
char * B;
int i, j;
AI = strlen(NA);
BI = strlen(NB);

A = (AI > BI) ? NA : NB;
B = (AI <= BI) ? NA : NB;
if (BI > AI)
{
int temp = BI;
BI = AI;
AI = temp;
}
C[0] = '0';
strcpy(C + 1, A);
j = BI - 1;
m = '0';
for (i = AI - 1; i >= 0; i--)
{
if (j >= 0)
{
C[i + 1] = AddChar(A[i], B[j], m);
m = AddM(A[i], B[j], m);
j--;
} else
{
if (m != '0')
9. Megoldsok 191
Heckl Istvn, PE www.tankonyvtar.hu
{
C[i + 1] = AddChar(A[i], '0', m);
m = AddM(A[i], '0', m);
}
}
}
C[0] = m;
if (C[0] == '0')
strcpy(C, C + 1);
}

void Read(FILE * fd)
{
char Num1[MAX_NUMBER_LENGTH];
char Num2[MAX_NUMBER_LENGTH];
char Num3[MAX_NUMBER_LENGTH];
fscanf(fd, "%s %s", Num1, Num2);
printf("%s + %s = ", Num1, Num2);
Add(Num1, Num2, Num3);
printf("%s\n", Num3);
}

int main()
{
FILE * fd = fopen(INPUT_FILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
Read(fd);
return 0;
}
3.21.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUT "datas.txt"

int Read(FILE * fd, int ** nums)
{
int count, i;
fscanf(fd, "%d", &count);
printf("%d numbers:\n", count);
*nums = (int *)malloc(sizeof(int) * count);
for (i = 0; i < count; i++)
{
fscanf(fd, "%d", (*nums) + i);
printf("%d ", (*nums)[i]);
}
printf("\n");
return count;
}

double Median(int count, int * A)
{
int i, j, pos, temp;
for (i = 0; i < count - 1; i++)
192 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
{
pos = i;
for (j = i; j < count; j++)
{
if (A[j] < A[pos])
pos = j;
}
temp = A[i];
A[i] = A[pos];
A[pos] = temp;
// printf("%d ", A[i]);
}

// printf("%d\n", A[count - 1]);
return count % 2 ? A[count / 2] : (A[ count / 2 - 1] + A[ count / 2]) /
2.0 ;
}

double Average(int count, int * A)
{
long int sum = 0;
int i;
for (i = 0; i < count; i++)
sum += A[i];
return (double)sum / count;
}

int main(int argc, char * argv[])
{
int count;
int * datas = NULL;
FILE * fd = fopen( argc > 0 ? argv[1] : DEFAULT_INPUT, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
count = Read(fd, &datas);
fclose(fd);
printf("The average is %g\n", Average(count, datas));
printf("The median is: %g\n", Median(count, datas));
free(datas);
return 0;
}
3.22.1.
#include <stdio.h>
#include <stdlib.h>

#define INPUT_FILE "students.txt"
#define MIN_AVERAGE 2.0
#define MIDDLE_AVERAGE 3.0
#define GOOD_AVERAGE 4.0
#define EXCELLENT_AVERAGE 4.5

#define MIN_BURSARY 15000
#define MIDDLE_BURSARY 20000
#define GOOD_BURSARY 25000
#define EXCELLENT_BURSARY 30000
9. Megoldsok 193
Heckl Istvn, PE www.tankonyvtar.hu

struct TSubject
{
int credit;
int mark;
};

struct TStudent
{
char Neptun[7];
int SubjNum;
struct TSubject * Subjects;
};

void ReadStudent(FILE * fd, struct TStudent * S)
{
int i;
fscanf(fd, "%s %d", S->Neptun, &S->SubjNum);
printf("Neptun: %s %d subjects\n", S->Neptun, S->SubjNum);
S->Subjects = (struct TSubject *)malloc(sizeof(struct TSubject) * S-
>SubjNum);
for (i = 0; i < S->SubjNum; i++)
fscanf(fd, "%d %d", &(S->Subjects + i)->credit, &(S->Subjects + i)-
>mark);
}

void Calc(struct TStudent * S, int SNum)
{
int i, j, sum;
int Credits, MaxCredits, Bursary;
double Average;
struct TSubject * Subj;
for (i = 0; i < SNum; i++)
{

Subj = S->Subjects;
Credits = MaxCredits = 0;
sum = 0;
for (j = 0; j < S->SubjNum; j++)
{
sum += Subj->credit * Subj->mark;
MaxCredits += Subj->credit;
if (Subj->mark >= 2)
Credits += Subj->credit;
Subj++;
}
Average = (double)sum / MaxCredits;
if (Average < MIN_AVERAGE)
Bursary = 0;
else if (Average < MIDDLE_AVERAGE)
Bursary = MIN_BURSARY;
else if (Average < GOOD_AVERAGE)
Bursary = MIDDLE_BURSARY;
else if (Average < EXCELLENT_AVERAGE)
Bursary = GOOD_BURSARY;
else Bursary = EXCELLENT_BURSARY;
printf("%s:\n\tCredits: %d/%d\n\tAverage: %g\n\tBursary: %d HUF\n",S-
>Neptun, MaxCredits, Credits, Average, Bursary);
S++;
194 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
}

int Read(FILE * fd, struct TStudent ** S)
{
int num, i;
fscanf(fd, "%d", &num);
*S = (struct TStudent *)malloc(sizeof(struct TStudent) * num);
for (i = 0; i < num; i++)
ReadStudent(fd, (*S) + i);
return num;
}

void FreeStudents(struct TStudent * S, int SNum)
{
int i;
for (i = 0; i < SNum; i++)
{
free(S[i].Subjects);
S[i].Subjects = NULL;
}
}

int main()
{
int StudentNum;
struct TStudent * Students;
FILE * fd = fopen(INPUT_FILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
StudentNum = Read(fd, &Students);
fclose(fd);
Calc(Students, StudentNum);
FreeStudents(Students, StudentNum);
return 0;
}
3.23.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LENGTH 100
#define DEFAULT_INPUTFILE "dune.txt"
#define DEFAULT_WORD "Atreides"
#define FALSE 0
#define TRUE 1

int CheckWord(char * W, int len)
{
int l = strlen(W);
int i;
for (i = len; i < l; i++)
{
if (((W[i] >= 'A') && (W[i] <= 'Z')) || ((W[i] >= 'a') && (W[i] <=
'z')))
9. Megoldsok 195
Heckl Istvn, PE www.tankonyvtar.hu
return FALSE;
}
return TRUE;
}

int SearchWord(FILE * fd, char * W)
{
int count = 0;
int len = strlen(W);
char ReadedWord[MAX_LENGTH]={0};
char BeforeWord[MAX_LENGTH]={0};
BeforeWord[0] = 0;
do
{
strcpy(BeforeWord, ReadedWord);
ReadedWord[0] = 0;
fscanf(fd, "%s", ReadedWord);
if (strncmp(ReadedWord, W, len) == 0)
{
if (CheckWord(ReadedWord, len))
{
printf("%s %s\n",BeforeWord, ReadedWord);
count++;
}
}
} while (!feof(fd));
return count;
}

int main(int argc, char *argv[])
{
char * FileName = argc > 1 ? argv[1] : DEFAULT_INPUTFILE;
char Word[MAX_LENGTH];
FILE * fd = fopen(FileName, "r");
if (fd == NULL)
{
perror(FileName);
return 0;
}
if (argc > 2)
strcpy(Word, argv[2]);
else
strcpy(Word, DEFAULT_WORD);
printf("%d hits\n", SearchWord(fd, Word));
fclose(fd);
return 0;
}
3.24.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "script.txt"
#define MAX_COMMAND_LEN 10
#define MAX_OPERAND_LEN 5

#define STOP_CMD "STOP"
#define GET_CMD "GET"
196 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
#define ADD_CMD "ADD"
#define SUB_CMD "SUB"
#define MUL_CMD "MUL"
#define DIV_CMD "DIV"
#define WRITE_CMD "WRITE"

void Get(FILE * fd, int * N)
{
char Op[MAX_OPERAND_LEN];
fscanf(fd, "%s", Op);
scanf("%d", N + (Op[0] - 'A'));
}

void WriteComment(FILE * fd)
{
char ch;
fscanf(fd, "%c", &ch);
do
{
fscanf(fd, "%c", &ch);
if (ch != '#')
printf("%c", ch);
} while (ch != '#');
}

void Add(FILE * fd, int * N)
{
char Op1[MAX_OPERAND_LEN];
char Op2[MAX_OPERAND_LEN];
char ch1, ch2;
fscanf(fd, "%s %s", Op1, Op2);
ch1 = Op1[0]; ch2 = Op2[0];
N[ ch1 - 'A' ] += N[ ch2 - 'A' ];
}

void Sub(FILE * fd, int * N)
{
char Op1[MAX_OPERAND_LEN];
char Op2[MAX_OPERAND_LEN];
char ch1, ch2;
fscanf(fd, "%s %s", Op1, Op2);
ch1 = Op1[0]; ch2 = Op2[0];
N[ ch1 - 'A' ] -= N[ ch2 - 'A' ];
}

void Mul(FILE * fd, int * N)
{
char Op1[MAX_OPERAND_LEN];
char Op2[MAX_OPERAND_LEN];
char ch1, ch2;
fscanf(fd, "%s %s", Op1, Op2);
ch1 = Op1[0]; ch2 = Op2[0];
N[ ch1 - 'A' ] *= N[ ch2 - 'A' ];
}

void Div(FILE * fd, int * N)
{
char Op1[MAX_OPERAND_LEN];
char Op2[MAX_OPERAND_LEN];
9. Megoldsok 197
Heckl Istvn, PE www.tankonyvtar.hu
char ch1, ch2;
fscanf(fd, "%s %s", Op1, Op2);
ch1 = Op1[0]; ch2 = Op2[0];
N[ ch1 - 'A' ] /= N[ ch2 - 'A' ];
}

void Write(FILE * fd, int * N)
{
char Op[MAX_OPERAND_LEN];
fscanf(fd, "%s", Op);
printf("%d\n", N[ Op[0] - 'A' ]);
}

void Run(FILE * fd)
{
int Numbers[3];
Numbers[0] = Numbers[1] = Numbers[2] = 0;
char Command[MAX_COMMAND_LEN];
do
{
fscanf(fd, "%s", Command);
if (strcmp(Command, "#") == 0)
WriteComment(fd);

if (strcmp(Command, GET_CMD) == 0)
Get(fd, Numbers);

if (strcmp(Command, ADD_CMD) == 0)
Add(fd, Numbers);

if (strcmp(Command, SUB_CMD) == 0)
Sub(fd, Numbers);

if (strcmp(Command, MUL_CMD) == 0)
Mul(fd, Numbers);

if (strcmp(Command, DIV_CMD) == 0)
Div(fd, Numbers);

if (strcmp(Command, WRITE_CMD) == 0)
Write(fd, Numbers);
} while (strcmp(Command, STOP_CMD) != 0);
}

int main(int argv, char * argc[])
{
FILE * fd = fopen(argv > 1 ? argc[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
Run(fd);
fclose(fd);
return 0;
}
3.25.1.
#include <stdio.h>
198 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
#include <stdlib.h>
#include <math.h>

#define DEFAULT_A 0
#define DEFAULT_B 1
#define DEFAULT_NUM 1000000

#define min(a, b) ((a) > (b)) ? ( b ) : ( a )
#define max(a, b) ((a) > (b)) ? ( a ) : ( b )

double f1(double x)
{
return sqrt( (2.0 - x) * x ) * 4.0;
}

double f2(double x)
{
return x * x;
}

void Integral(int a, int b, int num, double (*fptr)(double), char * funct
)
{
int i;
double res = 0.0;
double interval = b - a;
double mini = interval / num;
double t;
for (i = 0; i < num - 1; i++)
{
t = min(fptr(mini * i), fptr(mini * (i + 1))) * mini;
res += t;
}

printf("The Riemann integral of %s over x from %d to %d: %g\n", funct,
a, b, res);
}

int main(int argc, char * argv[])
{
int a, b, num;
a = argc > 1 ? atoi(argv[1]) : DEFAULT_A;
b = argc > 2 ? atoi(argv[2]) : DEFAULT_B;
num = argc > 3 ? atoi(argv[3]) : DEFAULT_NUM;
printf("\n");
Integral(a, b, num, f1, "f1(x) ");
Integral(a, b, num, f2, "f2(x) ");
Integral(a, b, num, sin, "sin(x) ");
Integral(a, b, num, tan, "tan(x) ");
printf("\n");
return 0;
}
3.26.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "polynoms.txt"
#define TRUE 1
9. Megoldsok 199
Heckl Istvn, PE www.tankonyvtar.hu
#define FALSE 0

struct TPolynom
{
int Degree;
int * A;
};

void InitPolynom(struct TPolynom * P)
{
P->Degree = 0;
P->A = NULL;
}

void FreePolynom(struct TPolynom * P)
{
free(P->A);
P->A = NULL;
P->Degree = 0;
}

void ReadPolynom(FILE * fd, struct TPolynom * P)
{
int i;
fscanf(fd, "%d", &(P->Degree));
printf("Degree: %d\n", P->Degree);
P->A = (int *)malloc(sizeof(int) * (P->Degree + 1));
for (i = 0; i <= P->Degree; i++)
fscanf(fd, "%d", P->A + i);
}

void PrintPolynom(struct TPolynom * P)
{
int first = TRUE;
int i;
for (i = 0; i < P->Degree; i++)
{
if (P->A[i] != 0)
{
if (!first)
{
first = TRUE;
if (P->A[i] > 0)
printf(" + ");
}
if (P->A[i] < 0)
printf(" - ");
first = FALSE;
if (abs(P->A[i]) == 1)
printf("x");
else
printf("%dx", abs(P->A[i]));
if (i < P->Degree - 1)
printf("^%d", P->Degree - i);
}
}
if (P->A[ P->Degree ] != 0)
{
if (first)
200 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
{
printf("%d", P->A[ P->Degree ]);
} else
{
if (P->A[ P->Degree ] < 0)
printf(" - %d", abs(P->A[ P->Degree ]));
else
printf(" + %d", abs(P->A[ P->Degree ]));
}
}
}

/* C = A + B */
void AddPolynom(struct TPolynom * A, struct TPolynom * B, struct TPolynom
* C)
{
int i;
if (C->A != NULL)
{
free(C->A);
InitPolynom(C);
}
int * Max = A->Degree > B->Degree ? A->A : B->A;
int * Min = A->Degree > B->Degree ? B->A : A->A;
int min = A->Degree > B->Degree ? B->Degree : A->Degree;
C->Degree = A->Degree > B->Degree ? A->Degree : B->Degree;
C->A = (int*)malloc(sizeof(int) * (C->Degree + 1));
for (i = 0; i <= C->Degree; i++)
C->A[i] = Max[i];
for (i = 0; i <= min; i++)
C->A[i + ( C->Degree - min ) ] += Min[i];
}

int main(int argc, char *argv[])
{
struct TPolynom A, B, C;
InitPolynom(&A);
InitPolynom(&B);
InitPolynom(&C);
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadPolynom(fd, &A);
ReadPolynom(fd, &B);
fclose(fd);
PrintPolynom(&A);
printf(" +\n");
PrintPolynom(&B);
printf(" =\n");
AddPolynom(&A, &B, &C);
PrintPolynom(&C);
printf("\n");
FreePolynom(&A);
FreePolynom(&B);
FreePolynom(&C);
return 0;
9. Megoldsok 201
Heckl Istvn, PE www.tankonyvtar.hu
}
3.27.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "codedmsg.txt"
#define WORD "THE"
#define MAX_WORD_LEN 15

typedef char TWord[MAX_WORD_LEN];

int ReadMessage(FILE * fd, TWord ** M)
{
int num, i;
fscanf(fd, "%d", &num);
(*M) = (TWord*)malloc(sizeof(TWord) * num);
for (i = 0; i < num; i++)
fscanf(fd, "%s", (*M)[i]);
return num;
}

void PrintMessage(TWord * M, int num)
{
int i;
for (i = 0; i < num; i++)
printf("%s ", M[i]);
printf("\n");
}

void Offset(TWord * M, int num, int offs)
{
int i, j, len;
for (i = 0; i < num; i++)
{
len = strlen(M[i]);
for (j = 0; j < len; j++)
{
M[i][j] += offs;
if (M[i][j] > 'Z')
M[i][j] -= ('Z' - 'A' + 1 );
}
}
}

void Decoding(TWord * M, int num)
{
int i = 0;
int j = num;
while ((i <= 'Z' - 'A') && (j >= num))
{
Offset(M, num, 1);
j = 0;
while ((j < num) && (strcmp(M[j], WORD) != 0))
j++;
}
}

202 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int main(int argc, char * argv[])
{
int num;
TWord * Message;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
num = ReadMessage(fd, &Message);
fclose(fd);
printf("\nThe coded message: ");
PrintMessage(Message, num);
Decoding(Message, num);
printf("The original message: ");
PrintMessage(Message, num);
printf("\n");
free(Message);
Message = NULL;
return 0;
}
3.27.2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "codedmsg.txt"
#define MAX_WORD_LEN 15

char WORD[500];

typedef char TWord[MAX_WORD_LEN];

int ReadMessage(FILE * fd, TWord ** M)
{
int num, i;
fscanf(fd, "%d", &num);
(*M) = (TWord*)malloc(sizeof(TWord) * num);
for (i = 0; i < num; i++)
fscanf(fd, "%s", (*M)[i]);
return num;
}

void PrintMessage(TWord * M, int num)
{
int i;
for (i = 0; i < num; i++)
printf("%s ", M[i]);
printf("\n");
}

void Offset(TWord * M, int num, int offs)
{
int i, j, len;
for (i = 0; i < num; i++)
{
len = strlen(M[i]);
9. Megoldsok 203
Heckl Istvn, PE www.tankonyvtar.hu
for (j = 0; j < len; j++)
{
M[i][j] += offs;
if (M[i][j] > 'Z')
M[i][j] -= ('Z' - 'A' + 1 );
}
}
}

void Decoding(TWord * M, int num)
{
int i = 0;
int j = num;
while ((i <= 'Z' - 'A') && (j >= num))
{
Offset(M, num, 1);
j = 0;
while ((j < num) && (strcmp(M[j], WORD) != 0))
j++;
}
}

int main(int argc, char * argv[])
{
int num;
TWord * Message;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
num = ReadMessage(fd, &Message);
fclose(fd);
printf("\nKnown word: ");
scanf("%s", WORD);
printf("\nThe coded message: ");
PrintMessage(Message, num);
Decoding(Message, num);
printf("The original message: ");
PrintMessage(Message, num);
printf("\n");
free(Message);
Message = NULL;
return 0;
}

// codedmsg.txt
WKH TXLFN IRA
3.28.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "cds.txt"
#define MAX_WORD_LENGTH 16
#define TRUE 1
#define FALSE 0
204 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

typedef char TWord[MAX_WORD_LENGTH];

struct TCD
{
int Num;
TWord Name;
TWord * P;
};

void ReadCD(FILE * fd, struct TCD * A)
{
int i;
fscanf(fd, "%s", A->Name);
fscanf(fd, "%d", &A->Num);
printf("%s:\n", A->Name);
A->P = (TWord *)malloc(sizeof(TWord) * A->Num);
for (i = 0; i < A->Num; i++)
{
fscanf(fd, "%s", A->P[i]);
printf("\t%s\n", A->P[i]);
}
}

int ReadCDs(FILE * fd, struct TCD ** A)
{
int num, i;
fscanf(fd, "%d", &num);
(*A) = (struct TCD * )malloc(sizeof(struct TCD) * num);
for (i = 0; i < num; i++)
ReadCD(fd, (*A) + i);
return num;
}

void Search(struct TCD * A, char * S, int num)
{
int i = 0;
int j;
int success = FALSE;
while ((i < num) && (!success))
{
j = 0;
while ((j < A[i].Num) && (strcmp(A[i].P[j], S) != 0))
j++;
success = j < A[i].Num;
i++;
}
if (success)
printf("The %s is here: %s\n", S, A[i - 1].Name);
else
printf("%s does not exists!\n", S);
}

void FreeCDs(struct TCD * A, int num)
{
int i;
for (i = 0; i < num; i++)
{
free(A[i].P);
9. Megoldsok 205
Heckl Istvn, PE www.tankonyvtar.hu
A[i].P = NULL;
}
}

int main(int argc, char * argv[])
{
int CDNum;
struct TCD * CDs;
TWord Word;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
CDNum = ReadCDs(fd, &CDs);
fclose(fd);
printf("Program name: ");
scanf(%s, Word);
Search(CDs, Word, CDNum);
FreeCDs(CDs, CDNum);
free(CDs);
CDs = NULL;
return 0;
}
3.28.2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "cds.txt"
#define MAX_WORD_LENGTH 16
#define TRUE 1
#define FALSE 0

typedef char TWord[MAX_WORD_LENGTH];

struct TCD
{
int Num;
TWord Name;
TWord * P;
};

void ReadCD(FILE * fd, struct TCD * A)
{
int i;
fscanf(fd, "%s", A->Name);
fscanf(fd, "%d", &A->Num);
printf("%s:\n", A->Name);
A->P = (TWord *)malloc(sizeof(TWord) * A->Num);
for (i = 0; i < A->Num; i++)
{
fscanf(fd, "%s", A->P[i]);
printf("\t%s\n", A->P[i]);
}
}

206 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int ReadCDs(FILE * fd, struct TCD ** A)
{
int num, i;
fscanf(fd, "%d", &num);
(*A) = (struct TCD * )malloc(sizeof(struct TCD) * num);
for (i = 0; i < num; i++)
ReadCD(fd, (*A) + i);
return num;
}

int spec_strcmp(const char* s1, const char* s2) {
int l1=strlen(s1), l2=strlen(s2);
int l=l1<l2?l1:l2,i;
for (i=0;i<l;i++) {
if (s1[i]!='?' && s1[i]!=s2[i] && s1[i]!='*') {
return -1;
}
}
return 0;
}

void Search(struct TCD * A, char * S, int num)
{
int i = 0;
int j;
int success = FALSE;
while ((i < num) && (!success))
{
j = 0;
while ((j < A[i].Num) && (spec_strcmp(A[i].P[j], S) != 0))
j++;
success = j < A[i].Num;
i++;
}
if (success)
printf("The %s is here: %s\n", S, A[i - 1].Name);
else
printf("%s does not exists!\n", S);
}

void FreeCDs(struct TCD * A, int num)
{
int i;
for (i = 0; i < num; i++)
{
free(A[i].P);
A[i].P = NULL;
}
}

int main(int argc, char * argv[])
{
int CDNum;
struct TCD * CDs;
TWord Word;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
9. Megoldsok 207
Heckl Istvn, PE www.tankonyvtar.hu
return 0;
}
CDNum = ReadCDs(fd, &CDs);
fclose(fd);
printf("Program name: ");
scanf("%s", Word);
Search(CDs, Word, CDNum);
FreeCDs(CDs, CDNum);
free(CDs);
CDs = NULL;
return 0;
}

// cds.txs
2
2007/11
2
BurningStudio
RadioRama
2005/4
3
Doc2PDF
Apollo
Stellarium
3.29.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "inventory.txt"
#define MAX_LENGTH 15
#define START_MONEY 10000

struct TGood
{
int count;
int purchaseprice;
int shopprice;
char name[MAX_LENGTH];
};

int ReadInventory(FILE * fd, struct TGood ** Good)
{
int num, i;
fscanf(fd, "%d", &num);
(*Good) = (struct TGood*)malloc(sizeof(struct TGood) * num);
for (i = 0; i < num; i++)
fscanf(fd, "%s %d %d %d", (*Good)[i].name, &(*Good)[i].count,
&(*Good)[i].purchaseprice, &(*Good)[i].shopprice);
return num;
}

void PrintInventory(struct TGood * G, int num)
{
int i;
printf("Inventory:\n****************************************\n");
for (i = 0; i < num; i++)
printf("%s:\n\tCount: %d\n\tPurchase price: %d\n\tShop price:
%d\n",
208 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
G[i].name, G[i].count, G[i].purchaseprice, G[i].shopprice);
}

int ReadLog(FILE * fd, int Money, int num, struct TGood * G)
{
int lognum, i;
int good, a;
fscanf(fd, "%d", &lognum);
for (i = 0; i < lognum; i++)
{
fscanf(fd, "%d %d", &good, &a);
G[good - 1].count += a;
if (a > 0) /* We buy the good */
Money -= abs(a) * G[good - 1].purchaseprice;
else /* We sell the good */
Money += abs(a) * G[good - 1].shopprice;
}
return Money;
}

int main(int argc, char *argv[])
{
struct TGood * Inventory;
int GoodNum;
int Money = START_MONEY;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
GoodNum = ReadInventory(fd, &Inventory);
PrintInventory(Inventory, GoodNum);
Money = ReadLog(fd, Money, GoodNum, Inventory);
PrintInventory(Inventory, GoodNum);
printf("We have got %d HUF\n", Money);
fclose(fd);
free(Inventory);
Inventory = NULL;
return 0;
}
3.30.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "lib1.txt"
#define MAXLEN 21
#define MAXUDC 4

// UDC = Universal Decimal Classification, in Hungarian: ETO

char * UDCClasses[10] = { "Generalities", "Philosophy, Psychology",
"Religion, Theology", "Social sciences",
"vacant", "Mathematics and natural sciences",
"Applied sciences, Medicine, Technology",
"Arts, Recreation, Entertainment, Sport" ,
"Language, Linguistics, Literature",
"Geography, Biography, History"};
9. Megoldsok 209
Heckl Istvn, PE www.tankonyvtar.hu

struct TBook
{
char title[MAXLEN];
char author[MAXLEN];
int edition;
char UDC[MAXUDC];
};

int ReadBooks(FILE * fd, struct TBook ** Books)
{
int num, i;
struct TBook * B;
fscanf(fd, "%d", &num);
(*Books) = B = (struct TBook*)malloc(sizeof(struct TBook) * num);
for (i = 0; i < num; i++)
{
fscanf(fd, "%s %s %d %s", B->title, B->author, &B->edition, B->UDC);
B++;
}
return num;
}

void CountBooks(struct TBook * B, int num)
{
int i;
int types[10];
for (i = 0; i < 10; i++)
types[i] = 0;
printf("\n\n");
for (i = 0; i < num; i++)
{
printf("Author: %s\n Title: %s\nYear of edition: %d\nUDC: %s %s\n\n",
B[i]. author, B[i].title, B[i].edition,
B[i].UDC, UDCClasses[ B[i].UDC[0] - '0' ]);
types[ B[i].UDC[0] - '0' ]++;
}
printf("\n**************************************\n\n");
for (i = 0; i < 10; i++)
printf("%s: %d books\n", UDCClasses[i], types[i]);
printf("\n\n");

}

int main(int argc, char * argv[])
{
int booknum;
struct TBook * Books;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
booknum = ReadBooks(fd, &Books);
fclose(fd);
CountBooks(Books, booknum);
free(Books);
Books = NULL;
210 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
return 0;
}
3.31.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "lib1.txt"
#define MAXLEN 20
#define YEAR 2008
#define MONTH 12
#define DAY 15
#define TRUE 1
#define FALSE 0

struct TBook
{
char title[MAXLEN];
char author[MAXLEN];
int year, month, day;
};

int ReadBooks(FILE * fd, struct TBook ** Books)
{
int num, i;
struct TBook * B;
fscanf(fd, "%d", &num);
(*Books) = B = (struct TBook*)malloc(sizeof(struct TBook) * num);
for (i = 0; i < num; i++)
{
fscanf(fd, "%s %s %d %d %d", B->title, B->author, &B->year, &B-
>month, &B->day);
B++;
}
return num;
}

int Later(int y, int m, int d)
{
if (y < YEAR)
return TRUE;
else if (y == YEAR)
{
if (m < MONTH)
return TRUE;
else if (m == MONTH)
{
if (d < DAY)
return TRUE;
}
}
return FALSE;
}

void PrintBooks(struct TBook * B, int num)
{
int i;
printf("\n");
for (i = 0; i < num; i++)
9. Megoldsok 211
Heckl Istvn, PE www.tankonyvtar.hu
{
if (Later(B[i].year, B[i].month, B[i].day))
printf("Title: %s\nAuthor: %s\nExpiraton: %d %d %d\n\n",
B[i].title, B[i].author, B[i].year, B[i].month, B[i].day);
}
}

int main(int argc, char * argv[])
{
int booknum;
struct TBook * Books;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
booknum = ReadBooks(fd, &Books);
fclose(fd);
PrintBooks(Books, booknum);
free(Books);
Books = NULL;
return 0;
}
3.32.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 21
#define DEFAULT_INPUTFILE "dict.txt"

void Search(FILE * fd, char * word)
{
int num, i, hits = 0;
char hword[MAXLEN], eword[MAXLEN];
fscanf(fd, "%d", &num);
eword[0] = 0;
for (i = 0; i < num; i++)
{
fscanf(fd, "%s %s", eword, hword);
if (strncmp(eword, word, strlen(word)) == 0)
{
printf("Eng->Hun: %s %s\n", eword, hword);
hits++;
}
if (strcmp(hword, word) == 0)
{
printf("Hun->Eng: %s %s\n", hword, eword);
hits++;
}
}
printf("\n%d hits\n\n", hits);
}

int main(int argc, char * argv[])
{
char word[MAXLEN];
212 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
printf("\nType the word: ");
scanf("%s", word);
Search(fd, word);
fclose(fd);
printf("\n");
return 0;
}
3.33.1.
#include <stdio.h>
#include <memory.h>

#define TRUE 1
#define FALSE 0
#define DEFAULT_INPUTFILE "sudoku1.txt"

typedef int TTable[9][9];

void ReadTable(FILE * fd, TTable T)
{
int i, j;
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
fscanf(fd, "%d", &T[i][j]);
}
}

void PrintTable(TTable T)
{
int i, j;
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
printf("%d ", T[i][j]);
printf("\n");
}
}

int CheckRowsColumns(TTable T)
{
int i, j, n, num;
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
n = i ? 0 : 1;
num = T[i][j];
while ((n < 9) && (T[n][j] != num))
n += (i == n + 1) ? 2 : 1;
if (n < 9)
{
printf("This is a wrong table!\n");
9. Megoldsok 213
Heckl Istvn, PE www.tankonyvtar.hu
return FALSE;
}

n = j ? 0 : 1;
num = T[i][j];
while ((n < 9) && (T[i][n] != num))
n += (j == n + 1) ? 2 : 1;
if (n < 9)
{
printf("This is a wrong table!\n");
return FALSE;
}
}
}
return TRUE;
}

int CheckOneCell(TTable T, int x, int y)
{
int i, j, num, err;
for (num = 1; num <= 9; num++)
{
err = TRUE;
for (i = y * 3; i < (y + 1) * 3; i++)
{
for (j = x * 3; j < (x + 1) * 3; j++)
{
if (T[i][j] == num)
err = FALSE;
}
}
if (err)
{
printf("This is a wrong table!\n");
return FALSE;
}
}
return TRUE;
}

void CheckCells(TTable T)
{
int i, j;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
if (!CheckOneCell(T, i, j))
return;
printf("This table is correct!\n");
}

void Check(TTable T)
{
if (CheckRowsColumns(T))
CheckCells(T);
}

int main(int argc, char * argv[])
{
TTable Table;
214 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadTable(fd, Table);
fclose(fd);
PrintTable(Table);
Check(Table);
return 0;
}
3.34.1.
#include <stdio.h>

#define FIRST_PLAYER 0
#define SECOND_PLAYER 1
#define TRUE 1
#define FALSE 0
#define SIGN1 'X'
#define SIGN2 'O'
#define SIZE 3
#define NUMTOWIN 3

typedef char TTable[SIZE][SIZE];

void InitTable(TTable T)
{
int i, j;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
T[i][j] = ' ';
}

void PrintTable(TTable T)
{
int i, j;
printf(" ");
for (i = 'A'; i < 'A' + SIZE; i++)
printf("%c ", i);
printf("\n");
printf(" -");
for (i = 0; i < SIZE; i++)
printf("--");
printf("\n");
for (i = 0; i < SIZE; i++)
{
printf("%2d|", i + 1);
for (j = 0; j < SIZE; j++)
printf("%c|", T[j][i]);
printf("\n ");
for (j = 0; j < SIZE; j++)
printf("--");
printf("-\n");
}

}

9. Megoldsok 215
Heckl Istvn, PE www.tankonyvtar.hu
int GetY(char y1, char y2)
{
return y2 > 0 ? (y1 - '0') * 10 + (y2 - '1') : y1 - '1' ;
}

int Drawn(TTable T)
{
int i, j;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
if (T[i][j] == ' ')
return FALSE;
return TRUE;
}

int Win(TTable T, char ch)
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (i <= SIZE - NUMTOWIN )
{
if ((T[i][j] == ch) && (T[i+1][j] == ch) && (T[i+2][j] ==
ch))
return TRUE;
}
if (j <= SIZE - NUMTOWIN )
{
if ((T[i][j] == ch) && (T[i][j+1] == ch) && (T[i][j+2] ==
ch))
return TRUE;
}
if ((i <= SIZE - NUMTOWIN ) && (j <= SIZE - NUMTOWIN ))
{
if ((T[i][j] == ch) && (T[i+1][j+1] == ch) && (T[i+2][j+2]
== ch))
return TRUE;
}
if ((i >= NUMTOWIN - 1 ) && (j <= SIZE - NUMTOWIN ))
{
if ((T[i][j] == ch) && (T[i-1][j+1] == ch) && (T[i-2][j+2]
== ch))
return TRUE;
}
}
}
return FALSE;
}

int WrongCoord(TTable T, char x, char y1, char y2)
{
int y = GetY(y1, y2);
if ((x < 'A') || (x >= 'A' + SIZE ) || (y < 0) || (y >= SIZE))
{
printf("Wrong coordinate!\n");
return TRUE;
}
216 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
if (T[x - 'A'][y] != ' ')
{
printf("You already cannot choose this position!\n");
return TRUE;
}
return FALSE;
}



void Play(TTable T)
{
char target[5];
int player = FIRST_PLAYER;
do
{
if (player == FIRST_PLAYER)
printf("First player\n");
else
printf("Second player\n");
printf("Target: ");
do
{
scanf("%s", target);
} while ((target[0] != '0') && WrongCoord(T, target[0], target[1],
target[2]));
if (target[0] != '0')
{
if (player == FIRST_PLAYER)
{
T[target[0] - 'A'][GetY(target[1], target[2])] = SIGN1;
if (Win(T, SIGN1))
{
PrintTable(T);
printf("First player won!\n");
return;
}
player = SECOND_PLAYER;
} else
{
T[target[0] - 'A'][GetY(target[1], target[2])] = SIGN2;
if (Win(T, SIGN2))
{
PrintTable(T);
printf("Second player won!\n");
return;
}
player = FIRST_PLAYER;
}
PrintTable(T);
}
} while ((target[0] != '0') && !Drawn(T));
printf("Game over!\n");
}

int main()
{
TTable Table;
InitTable(Table);
9. Megoldsok 217
Heckl Istvn, PE www.tankonyvtar.hu
PrintTable(Table);
Play(Table);
return 0;
}
3.35.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "map1.txt"
#define HILL 250
#define MOUNTAIN 500
#define HIGHMOUNTAIN 1500

struct TMap
{
int r, c;
int ** m;
};

void ReadMap(FILE * fd, struct TMap * M)
{
int i, j;
fscanf(fd, "%d %d", &M->r, &M->c);
M->m = (int**)malloc(sizeof(int*) * M->r);
for (i = 0; i < M->r; i++)
{
M->m[i] = (int*)malloc(sizeof(int) * M->c);
for (j = 0; j < M->c; j++)
fscanf(fd, "%d", &M->m[i][j]);
}
}

void FreeMap(struct TMap * M)
{
int i;
for (i = 0; i < M->r; i++)
{
free(M->m[i]);
M->m[i] = NULL;
}
free(M->m);
M->m = NULL;
}

void PrintMap(struct TMap * M)
{
int i, j;
printf("\nThe map:\n\n");
for (i = 0; i < M->r; i++)
{
for (j = 0; j < M->c; j++)
printf("%4d ", M->m[i][j]);
printf("\n");
}
}

void Count(struct TMap * M)
{
218 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int lowland = 0, hill = 0, mountain = 0, highmountain = 0;
int i, j, h;
double A = M->r * M->c;
for (i = 0; i < M->r; i++)
{
for (j = 0; j < M->c; j++)
{
h = M->m[i][j];
if (h < HILL)
lowland++;
else if (h < MOUNTAIN)
hill++;
else if (h < HIGHMOUNTAIN)
mountain++;
else highmountain++;
}
}
printf("\nLowland: %g %%\n", lowland / A * 100.0);
printf("Hill: %g %%\n", hill / A * 100.0);
printf("Mountain: %g %%\n", mountain / A * 100.0);
printf("High mountain: %g %%\n\n", highmountain / A * 100.0);
}

int main(int argc, char * argv[])
{
struct TMap Map;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadMap(fd, &Map);
fclose(fd);
PrintMap(&Map);
Count(&Map);
FreeMap(&Map);
return 0;
}
3.36.1.
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define SIZE 3

typedef double Matrix[SIZE][SIZE];

void PrintMatrix(Matrix m)
{
int i, j;
printf("\n");
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
printf("%2g ", m[i][j]);
printf("\n");
}
9. Megoldsok 219
Heckl Istvn, PE www.tankonyvtar.hu
printf("\n");
}

double GetDeterminant(Matrix m)
{
return m[0][0] * m[1][1] * m[2][2] +
m[0][1] * m[1][2] * m[2][0] +
m[0][2] * m[1][0] * m[2][1] -
m[0][2] * m[1][1] * m[2][0] -
m[0][1] * m[1][0] * m[2][2] -
m[0][0] * m[1][2] * m[2][1];
}

void MakeAdjMatrix(Matrix m)
{
int i, j, x1, y1, x2, y2;
Matrix m2;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
x1 = j == 0; // if j = 0, x1 = 1, if j = 1, x1 = 0, if j = 2, x1 =
0
y1 = i == 0;
// if j = 2, x2 = 1, if j = 1, x2 = 2, if j = 0, x2 = 2
x2 = (j != 2) + 1;
y2 = (i != 2) + 1;
m2[j][i] = (i + j) % 2 ? -1 : 1;
m2[j][i] *= (m[y1][x1] * m[y2][x2] - m[y1][x2] * m[y2][x1]);
}
}
memcpy(m, m2, sizeof(double) * SIZE * SIZE);
}

void InvertMatrix(Matrix m)
{
int i, j;
double det;
det = GetDeterminant(m);
printf("Adjugate matrix: \n");
MakeAdjMatrix(m);
PrintMatrix(m);

printf("Determinant of the matrix: %g\n", det);
if (det != 0.0)
{
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
m[i][j] /= det;
}
printf("Inverse matrix: \n");
PrintMatrix(m);
} else printf("We cannot invert this matrix!\n");
}

int main()
{
Matrix matrix= { {1, 2, 3},
220 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
{2, 4, 5},
{3, 5, 6} };
printf("Original matrix:\n");
PrintMatrix(matrix);
InvertMatrix(matrix);
return 0;
}
3.37.1.
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "matrices1.txt"

struct TMatrix
{
int r,c;
int ** m;
};

void InitMatrix(struct TMatrix * M, int r, int c)
{
int i,j;
M->r = r;
M->c = c;
M->m = (int**)malloc(sizeof(int*) * r);
for (i = 0; i < r; i++)
{
M->m[i] = (int*)malloc(sizeof(int) * c);
for (j = 0; j < c; j++)
M->m[i][j] = 0;
}
}

void FreeMatrix(struct TMatrix * M)
{
int i;
for (i = 0; i < M->r; i++)
{
free(M->m[i]);
M->m[i] = NULL;
}
free(M->m);
M->m = NULL;
M->r = M-> c = 0;
}

void PrintMatrix(struct TMatrix * M)
{
int i, j;
for (i = 0; i < M->r; i++)
{
for (j = 0; j < M->c; j++)
printf("%3d ", M->m[i][j]);
printf("\n\n\n");
}
}

void ReadMatrix(FILE * fd, struct TMatrix * M)
9. Megoldsok 221
Heckl Istvn, PE www.tankonyvtar.hu
{
int i, j;
for (i = 0; i < M->r; i++)
{
for (j = 0; j < M->c; j++)
fscanf(fd, "%d", &M->m[i][j]);
}
}

void AddMulMatrix(struct TMatrix * A, struct TMatrix * B, struct TMatrix
* C, int m)
{
int i, j;
for (i = 0; i < A->r; i++)
{
for (j = 0; j < A->c; j++)
C->m[i][j] = (A->m[i][j] + B->m[i][j]) * m;
}
}

int main(int argc, char *argv[])
{
struct TMatrix A, B, C;
int r, c;
FILE * fd = fopen( argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
fscanf(fd, "%d %d", &r, &c);
InitMatrix(&A, r, c);
InitMatrix(&B, r, c);
InitMatrix(&C, r, c);
ReadMatrix(fd, &A);
ReadMatrix(fd, &B);
fclose(fd);
printf("A : \n\n");
PrintMatrix(&A);
printf("B : \n\n");
PrintMatrix(&B);
AddMulMatrix(&A, &B, &C, 2);
printf("************************\n (A + B) * 2 = \n\n");
PrintMatrix(&C);
FreeMatrix(&A);
FreeMatrix(&B);
FreeMatrix(&C);
return 0;
}
3.38.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SZOKOZ "....."

char * morsecodes[26] = { ".=", "=...", "=.=.", // A, B, C
"=..", ".", "..=.", // D, E, F
222 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
"==.", "....", "..", // G, H, I
".===", "=.=", ".=..", // J, K, L
"==", "=.", "===", // M, N, O
".==.", "==.=", ".=.", // P, Q, R
"...", "=", "..=", // S, T, U
"...=", ".==", "=..=", // V, W, X
"=.==", "==.."}; // Y, Z

void getline(char * s, int maxlen)
{
char ch;
int i = 0;
do
{
ch = getchar();
if (ch!='\n')
s[i++] = ch;
}
while ((i < maxlen - 1) && (ch!='\n'));
s[i] = 0;
}

char * coding(char * s)
{
int len = 1;
int i;
char * c;
for (i = 0; i < strlen(s); i++)
if (s[i] != ' ')
len += strlen(morsecodes[ s[i] - 'A' ]);
else
len += strlen(SZOKOZ);
c = (char*)malloc(sizeof(char) * len);
//printf("len: %d\n", len);
len = 0;
for (i = 0; i < strlen(s); i++)
{
if (s[i] != ' ')
{
//printf("char: %c index: %d code: %s\n", s[i], s[i] - 'A',
morsecodes[ s[i] - 'A']);
strcpy(c + len, morsecodes[ s[i] - 'A' ]);
len += strlen(morsecodes[ s[i] - 'A' ]);
} else
{
strcpy(c + len, SZOKOZ);
len += strlen(SZOKOZ);
}
}
c[len] = 0;
return c;
}

int main()
{
char message[100];
char * morse;
printf("The message: ");
getline(message, 100);
9. Megoldsok 223
Heckl Istvn, PE www.tankonyvtar.hu
printf("Message: \"%s\" \n", message);
morse = coding(message);
printf("The coded message: \"%s\"\n", morse);
free(morse);
morse = NULL;
return 0;
}
3.39.1
#include <stdio.h>
#include <stdlib.h>

#define DEFAULT_INPUTFILE "input.txt"

struct TMatrix
{
int r,c;
int ** m;
};

void InitMatrix(struct TMatrix * M, int r, int c)
{
int i,j;
M->r = r;
M->c = c;
M->m = (int**)malloc(sizeof(int*) * r);
for (i = 0; i < r; i++)
{
M->m[i] = (int*)malloc(sizeof(int) * c);
for (j = 0; j < c; j++)
M->m[i][j] = 0;
}
}

void FreeMatrix(struct TMatrix * M)
{
int i;
for (i = 0; i < M->r; i++)
{
free(M->m[i]);
M->m[i] = NULL;
}
free(M->m);
M->m = NULL;
M->r = M-> c = 0;
}

void PrintMatrix(struct TMatrix * M)
{
int i, j;
for (i = 0; i < M->r; i++)
{
for (j = 0; j < M->c; j++)
printf("%3d ", M->m[i][j]);
printf("\n\n\n");
}
}

void ReadMatrix(FILE * fd, struct TMatrix * M)
224 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
{
int i, j;
for (i = 0; i < M->r; i++)
{
for (j = 0; j < M->c; j++)
fscanf(fd, "%d", &M->m[i][j]);
}
}

void AddMulMatrix(struct TMatrix * A, struct TMatrix * B, struct TMatrix
* C, int m)
{
int i, j;
for (i = 0; i < A->r; i++)
{
for (j = 0; j < A->c; j++)
C->m[i][j] = (A->m[i][j] + B->m[i][j]) * m;
}
}

void MulMatrixVector(struct TMatrix * M, struct TMatrix * V1, struct
TMatrix * V2)
{
int i, j;
for (i = 0; i < M->r; i++)
{
V2->m[i][0] = 0;
for (j = 0; j < M->c; j++)
V2->m[i][0] += M->m[i][j] * V1->m[j][0];
}
}

int main(int argc, char *argv[])
{
struct TMatrix A, V1, V2;
int r, c;
FILE * fd = fopen( argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
fscanf(fd, "%d %d", &r, &c);
InitMatrix(&A, r, c);
InitMatrix(&V1, c, 1);
InitMatrix(&V2, r, 1);
ReadMatrix(fd, &A);
ReadMatrix(fd, &V1);
fclose(fd);
MulMatrixVector(&A, &V1, &V2);
printf("Matrix : \n\n");
PrintMatrix(&A);
printf("Vector : \n\n");
PrintMatrix(&V1);
printf("************************\n Matrix * Vector = \n\n");
PrintMatrix(&V2);
FreeMatrix(&A);
FreeMatrix(&V1);
FreeMatrix(&V2);
9. Megoldsok 225
Heckl Istvn, PE www.tankonyvtar.hu
return 0;
}
3.40.1.
#include <stdio.h>
#include <stdlib.h>

#define MAXLEN 101

int Count(char * str)
{
int szkzs = 0;
int i;
for (i = 0; str[i] != 0; i++)
szkzs += (str[i] == ' ');
return ++szkzs;
}

char * GetToken(char * s, int * len)
{
int i = 0;
char * w;
*len = 0;
while ((s[ *len ] != 0) && (s[ *len ] != ' '))
(*len)++;

(*len)++;
w = (char*)malloc(sizeof(char) * (*len));
for (i = 0; i < (*len) - 1; i++)
w[i] = s[i];
w[(*len) - 1] = 0;
return w;
}

char ** Tokenizer(char * str, int * s)
{
int i;
int size = Count(str);
int len;
char ** t = (char **)malloc(size * sizeof(char*));
for (i = 0; i < size; i++)
{
t[i] = GetToken(str, &len);
str += len;
}
*s = size;
return t;
}

void Print(char ** t, int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d.: \"%s\"\n", i + 1, t[i]);
}

void Free(char *** t, int size)
{
int i;
226 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
char ** t2 = *t;
for (i = 0; i < size; i++)
{
free(t2[i]);
t2[i] = NULL;
}
*t = NULL;
}

int main()
{
char str[MAXLEN];
char ** t = NULL;
int size;
if (gets(str) == NULL)
{
printf("Error!\n");
return 0;
}
printf("The typed text: \"%s\"\n", str);
t = Tokenizer(str, &size);
Print(t, size);
Free(&t, size);

return 0;
}
3.41.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "text.txt"
#define MAX_TEXT_LENGTH 1001
#define MAX_WORD_LENGTH 21
#define TRUE 1
#define FALSE 0

void Change(char * t, char * w1, char * w2)
{
int i = 0;
int j;
int lent = strlen(t);
int lenw = strlen(w1);
int lenw2 = strlen(w2);
char tmp;
int hits = 0;
for (i = 0; i < lent - lenw; i++)
{
if (strncmp(t + i, w1, lenw) == 0)
{
tmp = t[i + lenw2];
strcpy(t + i, w2);
t[i + lenw2] = tmp;
for (j = i + lenw2; j < lent - (lenw - lenw2); j++)
t[j] = t[j + lenw - lenw2];
t[j] = 0;
lent = strlen(t);
hits++;
9. Megoldsok 227
Heckl Istvn, PE www.tankonyvtar.hu
}
}
printf("\n%d hits\n", hits);
}

int main(int argc, char * argv[])
{
char text[MAX_TEXT_LENGTH];
char word1[MAX_WORD_LENGTH];
char word2[MAX_WORD_LENGTH];
FILE * fd = fopen(argc > 1? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
if (fgets(text, MAX_TEXT_LENGTH - 1, fd) == NULL)
{
perror("Error");
fclose(fd);
return 0;
}
fclose(fd);
printf("\nThe original text: \"%s\"\n\n", text);
printf("Type a word: ");
scanf("%s", word1);
printf("Type the new word: ");
scanf("%s", word2);
Change(text, word1, word2);
printf("\nThe new text: \"%s\"\n\n", text);
return 0;
}
3.42.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "message.txt"
#define TRUE 1
#define FALSE 0
#define MAXLEN 51

typedef unsigned char ubyte;

ubyte GetChecksum(char * msg)
{
unsigned short sum = 0;
int i;
for (i = 0; msg[i] != 0; i++)
sum += (unsigned char)msg[i];
printf("\nSum of \"%s\": %X\n", msg, sum);
// drop the carry
sum = (ubyte)sum;
// two's complement:
sum = 0xFF - sum + 1;
printf("The checksum: %X\n", sum);
return sum;
}
228 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

int Checking(char * msg, ubyte chksm)
{
int i;
unsigned short sum = chksm;
for (i = 0; msg[i] != 0; i++)
sum += (unsigned char)msg[i];
sum = (ubyte)sum;
return (sum == 0);
}

void ReadMessages(FILE * fd)
{
int count;
int i;
unsigned int chksum;
char msg[MAXLEN];
fscanf(fd, "%d\n", &count);
printf("\n");
for (i = 0; i < count; i++)
{
if (fgets(msg, MAXLEN, fd) == NULL)
{
printf("Error\n");
return;
}
msg[strlen(msg) - 1] = 0;
fscanf(fd, "%X\n", &chksum);
printf("\"%s\" %X ===> ", msg, chksum);
if (Checking(msg, chksum))
printf("Correct!\n");
else
printf("Faulty!\n");
}
}

int main(int argc, char * argv[])
{
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror("Error");
return 0;
}
ReadMessages(fd);
fclose(fd);
GetChecksum("This is a simple checksum example.");
printf("\n");
return 0;
}
3.43.1.-3.34.3.
#include <stdio.h>
#include <stdlib.h>

#define AKTUALIS_EV 2010

int main(int argc, char** argv) {

9. Megoldsok 229
Heckl Istvn, PE www.tankonyvtar.hu
FILE * fd = fopen(argv[1], "r");
if (fd == NULL) {
perror("Hiba");
return EXIT_FAILURE;
}
int kiskoru = 0;
int felnott = 0;
int nyugdijas = 0;
int vh2 = 0;
int szokoevben = 0;
int eletkor;
while (!feof(fd)) {

if (fscanf(fd, "%d", &eletkor)) {
// 4.30.1:
if (eletkor < 18) {
kiskoru++;
} else {
felnott++;
if (eletkor >= 62) {
nyugdijas++;
}
}
// 4.30.2:
int ev = AKTUALIS_EV - eletkor;
if (ev >= 1939 && ev <= 1945) {
vh2++;
}
// 4.30.3:
printf("ev: %d\n", ev);
if ((ev % 400 == 0) || (ev % 4 == 0 && ev % 100 != 0)) {
printf("szokoev\n");
szokoevben++;
}
}
}
fclose(fd);

printf("Kiskoruak: %d\n", kiskoru);
printf("Felnottek: %d\n", felnott);
printf("Nyugdijasok: %d\n", nyugdijas);
printf("Vilaghaboru alatt: %d\n", vh2);
printf("Szokoevben: %d\n", szokoevben);
return EXIT_SUCCESS;
}

// input.txt
3
20
30
3
5
23
53
63
13
70
80
43
230 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
23
64
23
64
2
3
10
32
53
110
3.44.1.
#include <stdio.h>
#include <stdlib.h>

int main() {
int koteg;
int osszeg = 0;
do {
printf("Kerem a keriteskoteg hosszat: ");
scanf("%d", &koteg);
osszeg += koteg;
} while (koteg > 0);
printf("Osszesen van %d meter kerites\n", osszeg);
if (osszeg < 400) {
printf("Meg kell %d meternyi kerites\n", 400 - osszeg);
}
return EXIT_SUCCESS;
}
3.45.1.
#include <stdio.h>
#include <stdlib.h>

#define N 10

int main() {
int i;
int osszeg = 0;
int jegy;
for (i = 0; i < N; i++) {
printf("%d. jegy: ", i + 1);
scanf("%d", &jegy);
osszeg += jegy;
}
printf("A jegyek szamtani atlaga: %g\n", (double)osszeg / N);
return EXIT_SUCCESS;
}
3.45.2-3.45.3.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define N 10

typedef struct lista {
struct lista * kovetkezo;
int jegy;
9. Megoldsok 231
Heckl Istvn, PE www.tankonyvtar.hu
} lista;

int main() {
lista * jegyek = NULL;
int i;
int osszeg = 0;
int jegy;
double atlag;
i = 1;

do {
printf("%d. jegy: ", i++);
scanf("%d", &jegy);
osszeg += jegy;
if (jegy > 0) {
lista * elem = (lista *) malloc(sizeof (lista));
elem->jegy = jegy;
if (jegyek == NULL) {
elem->kovetkezo = NULL;
} else {
elem->kovetkezo = jegyek;
}
jegyek = elem;
}
} while (jegy > 0);
atlag = (double) osszeg / (i - 2);

lista * temp = jegyek;
lista * prev;
double elteres = 0;
while (temp != NULL) {
elteres += (atlag - temp->jegy) * (atlag - temp->jegy);
prev = temp;
temp = temp->kovetkezo;
free(prev);
}
double szoras = sqrt(elteres / (i - 2));

printf("A jegyek szamtani atlaga: %g\n", atlag);
printf("A jegyek szorasa: %g\n", szoras);
return EXIT_SUCCESS;
}
3.46.1.-3.46.2.
#include <stdio.h>
#include <stdlib.h>

int main() {
unsigned long long int termekeny = 0, termeketlen = 1;
unsigned long long int osszesen = termeketlen;
int honap;
int ev;
for (ev = 1; ev <= 5; ev++) {
for (honap = 1; honap <= 12; honap++) {
unsigned long long int nyulakUj = termekeny + termeketlen;
osszesen += nyulakUj;
termekeny = termeketlen;
termeketlen = nyulakUj;
printf("%d\n", nyulakUj);
232 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}

termekeny *= 0.1;
termeketlen *= 0.05;
printf("eladas utan %llu termekeny es %llu termeketlen nyulpar
van\n",
termekeny, termeketlen);

printf("Osszesen %llu adag tapra lesz szukseg\n", osszesen * 2);
}
return EXIT_SUCCESS;
}
3.47.1.
#include <stdio.h>
#include <stdlib.h>

#define N 30

int main() {
double jegyek[N];
int i;
for (i = 0; i < N; i++) {
printf("A %d. atlag: ", i + 1);
scanf("%lf", &jegyek[i]);
}

i = 0;
while (i < N && jegyek[i] >= 1.5) {
i++;
}
if (i < N) {
printf("Volt bukas!\n");
} else {
printf("Nem volt bukas!\n");
}
return EXIT_SUCCESS;
}
3.47.2.
#include <stdio.h>
#include <stdlib.h>

int main() {
double jegy;
int sorszam = 1;
do {
printf("Kerem a %d. atlagot: ", sorszam++);
scanf("%lf", &jegy);
} while (jegy >= 1.5);
if (jegy == 0.0 || jegy >= 1.5) {
printf("Nem volt bukas!\n");
} else {
printf("Volt bukas!\n");
}
return EXIT_SUCCESS;
}
9. Megoldsok 233
Heckl Istvn, PE www.tankonyvtar.hu
3.48.1.
#include <stdio.h>
#include <stdlib.h>

#define N 100

int main() {
double magassag[N];
int i;
for (i = 0; i < N; i++) {
magassag[i] = (rand() % 1000) / 10.0;
}

int minIndex = 0;
int maxIndex = 0;
for (i = 0; i < N; i++) {
if (magassag[minIndex] > magassag[i]) {
minIndex = i;
}
if (magassag[maxIndex] < magassag[i]) {
maxIndex = i;
}
}
printf("A legmagasabb pont: %g, helye: %d\n", magassag[maxIndex],
maxIndex);
printf("A legalacsonyabb pont: %g, helye: %d\n", magassag[minIndex],
minIndex);
return EXIT_SUCCESS;
}
3.48.2.-3.48.4.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define N 100

double magassagLekerdez() {
static int i = 0;
double res;
if (i >= 0 && i <= 3)
res = 4;
else if (i >= 4 && i <= 10)
res = 3;
else if (i >= 40 && i <= 60)
res = 7;
else if (i >= 70 && i <= 100)
res = 2;
else
res = (rand() % 1000) / 10.0;
i++;
return res;
}

typedef struct Siksag {
int kezdet;
int veg;
int hossz;
} Siksag;
234 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

int main() {
int i;
int minIndex = 0;
int maxIndex = 0;
int emelkedoIndex;
Siksag maxSiksag;
Siksag aktSiksag;
double minMagassag;
double maxMagassag;
double maxKulonbseg = 0;
double magassag;
double elozo;
maxSiksag.hossz = 1;
maxSiksag.veg = 0;
for (i = 0; i < N; i++) {
magassag = magassagLekerdez();
if (i == 0) {
minMagassag = magassag;
maxMagassag = magassag;
elozo = magassag;
} else {
if (abs(elozo - magassag) > maxKulonbseg) {
maxKulonbseg = abs(elozo - magassag);
emelkedoIndex = i;
}
if (minMagassag > magassag) {
minIndex = i;
minMagassag = magassag;
}
if (maxMagassag < magassag) {
maxIndex = i;
maxMagassag = magassag;
}

if (elozo == magassag) {
if (aktSiksag.hossz == 0) {
aktSiksag.hossz = 2;
aktSiksag.kezdet = i - 1;
aktSiksag.veg = i;
} else {
aktSiksag.veg = i;
aktSiksag.hossz++;
}
} else {
if (aktSiksag.veg == i - 1) {
if (maxSiksag.hossz < aktSiksag.hossz) {
maxSiksag = aktSiksag;
}
aktSiksag.hossz = 0;
}
}

elozo = magassag;
}
}
if (maxSiksag.hossz < aktSiksag.hossz && aktSiksag.hossz > 1) {
maxSiksag = aktSiksag;
}
9. Megoldsok 235
Heckl Istvn, PE www.tankonyvtar.hu

double maxFok = atan(maxKulonbseg / 100.0) / (M_PI / 180.0);
printf("A legmagasabb pont: %g, helye: %d\n", maxMagassag, maxIndex);
printf("A legalacsonyabb pont: %g, helye: %d\n", minMagassag,
minIndex);
printf("A legmeredekebb emelkedo: %g fok, helye: %d\n", maxFok,
emelkedoIndex);

printf("A leghosszabb siksag adatai:\n\tkezdete: %d\n\tvege:
%d\n\thossza: %d\n",
maxSiksag.kezdet, maxSiksag.veg, maxSiksag.hossz);
return EXIT_SUCCESS;
}
3.49.1-3.49.3.
#include <stdio.h>
#include <stdlib.h>

typedef struct Elem {
double value;
int index;
struct Elem * next;
} Elem;

typedef struct Vector {
Elem * fej;
} Vector;

void initVector(Vector * vector) {
vector->fej = NULL;
}

double lekerdezVector(Vector vector, int index) {
Elem * tmp = vector.fej;
while (tmp && tmp->index < index)
tmp = tmp->next;
if (tmp && tmp->index == index)
return tmp->value;
return 0.0;
}

int torolVector(Vector * vector, int pos) {
Elem * prv = 0, * tmp = vector->fej;
while (tmp && tmp->index < pos) {
prv = tmp;
tmp = tmp->next;
}
if (tmp && tmp->index == pos) {
if (prv)
prv->next = tmp->next;
else
vector->fej = tmp->next;
free(tmp);
return 1;
}
return 0;
}

void tisztitVector(Vector * vector) {
236 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
Elem * tmp = vector->fej, * prv = 0;
while (tmp) {
if (tmp->value == 0) {
Elem * tmp2 = tmp->next;
torolVector(vector, tmp->index);
tmp = tmp2;
} else {
prv = tmp;
tmp = tmp->next;
}
}
}

void felszabaditVector(Vector * vector) {
Elem * tmp1 = vector->fej;
Elem * tmp2;
while (tmp1) {
tmp2 = tmp1->next;
free(tmp1);
tmp1 = tmp2;
}
vector->fej = 0;
}

void mutatVector(Vector vector) {
int i, dim;
if ((dim = legutolsoVector(vector)) == 0) {
printf("ures\n");
return;
}
for (i = 0; i <= dim; i++) {
printf("%lg", lekerdezVector(vector, i));
if (i < dim)
printf(",");
}
printf("\n");
}

void beallitVector(Vector * vector, double value, int pos) {
if (value == 0.0)
return;
if (!vector->fej) {
vector->fej = (Elem*) malloc(sizeof (Elem));
vector->fej->value = value;
vector->fej->index = pos;
vector->fej->next = 0;
} else {
Elem * prv = NULL, * tmp = vector->fej;
while (tmp && (tmp->index < pos)) {
prv = tmp;
tmp = tmp->next;
}
if (tmp && tmp->index == pos) {
tmp->value = value;
return;
}
Elem * nm = (Elem*) malloc(sizeof (Elem));
nm->value = value;
nm->index = pos;
9. Megoldsok 237
Heckl Istvn, PE www.tankonyvtar.hu
if (!tmp) {
prv->next = nm;
prv->next->next = 0;
} else {
if (prv) {
prv->next = nm;
prv->next->next = tmp;
} else {
prv = nm;
prv->next = tmp;
vector->fej = prv;
}
}
}
}

void rendezVector(Vector vector) {
if (!vector.fej)
return;
Elem * tmp1, * tmp2, * min;
double temp;
tmp1 = vector.fej;
while (tmp1->next) {
min = tmp2 = tmp1;
while (tmp2) {
if (tmp2->value < min->value)
min = tmp2;
tmp2 = tmp2->next;
}
temp = min->value;
min->value = tmp1->value;
tmp1->value = temp;
tmp1 = tmp1->next;
}
}

double szorozVector(Vector v1, Vector v2) {
if (!v1.fej || !v2.fej)
return 0.0;
double res = 0;
Elem * tmp1 = v1.fej;
while (tmp1) {
Elem * tmp2 = v2.fej;
while (tmp2 && tmp2->index < tmp1->index)
tmp2 = tmp2->next;
if (tmp2 && tmp2->index == tmp1->index)
res += tmp1->value * tmp2->value;
tmp1 = tmp1->next;
}
return res;
}

void addVector(Vector * v1, Vector v2) {
Elem * tmp1 = v1->fej, * tmp2;
while (tmp1) {
tmp2 = v2.fej;
while (tmp2 && tmp2->index < tmp1->index)
tmp2 = tmp2->next;
if (tmp2 && tmp2->index == tmp1->index)
238 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
tmp1->value += tmp2->value;
tmp1 = tmp1->next;
}
tmp1 = v2.fej;
while (tmp1) {
tmp2 = v1->fej;
while (tmp2 && tmp2->index < tmp1->index)
tmp2 = tmp2->next;
if (!tmp2 || tmp2->index > tmp1->index)
beallitVector(v1, tmp1->value, tmp1->index);
tmp1 = tmp1->next;
}
tisztitVector(v1);
}

int meretVector(Vector vector) {
Elem * tmp = vector.fej;
int count = 0;
while (tmp) {
count++;
tmp = tmp->next;
}
return count;
}

int legutolsoVector(Vector vector) {
Elem * tmp = vector.fej;
int dim = 0;
while (tmp) {
dim = tmp->index;
tmp = tmp->next;
}
return dim;
}

int menuMutat() {
int menu;
printf("Beallit: 1\n");
printf("Ertek: 2\n");
printf("Mindet torol: 3\n");
printf("Nem nullak szama: 4\n");
printf("Legutolso: 5\n");
printf("Megjelenit: 6\n");
printf("Rendez: 7\n");
printf("Hozzaad: 8\n");
printf("Szoroz: 9\n");
printf("Kilepes: 10\n");
scanf("%d", &menu);
return menu;
}

int main() {
Vector vector;
initVector(&vector);
Vector v2;
initVector(&v2);
beallitVector(&v2, 5, 2);
beallitVector(&v2, 1, 6);
beallitVector(&v2, 7, 10);
9. Megoldsok 239
Heckl Istvn, PE www.tankonyvtar.hu

int menu;

do {
menu = menuMutat();
if (menu == 1) {
int index;
double ertek;
printf("Hanyadik elem? ");
scanf("%d", &index);
printf("Ertek? ");
scanf("%lg", &ertek);
beallitVector(&vector, ertek, index);
}
if (menu == 2) {
int index;
printf("Hanyadik elem? ");
scanf("%d", &index);
printf("A(z) %d. elem: %g\n\n", index, lekerdezVector(vector,
index));
}
if (menu == 3) {
felszabaditVector(&vector);
}
if (menu == 4) {
printf("Nem nullak szama: %d\n\n", meretVector(vector));
}
if (menu == 5) {
printf("Legnagyobb nem nulla index: %d\n\n",
legutolsoVector(vector));
}
if (menu == 6) {
mutatVector(vector);
}
if (menu == 7) {
rendezVector(vector);
}
if (menu == 8) {
addVector(&vector, v2);
}
if (menu == 9) {
printf("A skalaris szorzat: %lg\n", szorozVector(vector,
v2));
}
} while (menu != 10);

felszabaditVector(&vector);
felszabaditVector(&v2);
return EXIT_SUCCESS;
}
4.1.1.
#include <stdio.h>
const int listSize=7;

void printList(int head, int* listIndex, double* listData) {
int act=head;
printf("[");
while (act != -1) {
240 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("%4.2lf", listData[act]);
act = listIndex[act]; // next element
if (act != -1)
printf(",");
}
printf("]");
}

void deleteLast(int* head, int* listIndex, double* listData) {
int act= *head, prev, prev2;
if (act== -1) // list already empty
return;
if (listIndex[act]== -1) { // list had 1 element
*head = -1;
return;
}
prev2 = act; // list had more elements
act = listIndex[act];
prev = act; // list had more elements
act = listIndex[act];
while (act != -1) {
prev2 = prev;
prev = act;
act = listIndex[act]; // next element
}
// now act == -1 (pass the end pointer)
// prev - pointer of the last element
// prev2 - pointer of last but one element
listIndex[prev2] = -1;
}

int main() {
double listData[listSize]={34, 12.55, 893.2, 2, 11.6, 47.5, 45.3};
int listIndex[listSize]={-1, 0, 4, 1, 6, 3, 5};
int head=2;

printf("list: ");
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
9. Megoldsok 241
Heckl Istvn, PE www.tankonyvtar.hu
printf("\n");
deleteLast(&head, listIndex, listData);
printList(head, listIndex, listData);
return 0;
}
// Ha trls utn elemet akarunk beszrni,
// akkor clszer kln listban trolni a szabad elemeket
4.1.2.
#include <stdio.h>
#include <stdlib.h>
const int listSize = 7;

void printList(int head, int* listIndex, double* listData) {
int act = head;
printf("[");
while (act != -1) {
printf("%4.2lf", listData[act]);
act = listIndex[act]; // next element
if (act != -1)
printf(", ");
}
printf("]\n");
}

void deleteLast(int* head, int* listIndex, double* listData) {
int act = *head, prev, prev2;
if (act == -1) // list already empty
return;
if (listIndex[act] == -1) { // list had 1 element
*head = -1;
return;
}
prev2 = act; // list had more elements
//act = listIndex[act];
prev = act = listIndex[act]; // list had more elements
act = listIndex[act];
while (act != -1) {
prev2 = prev;
prev = act;
act = listIndex[act]; // next element
}
// now act == -1 (pass the end pointer)
// prev - pointer of the last element
// prev2 - pointer of last but one element
listIndex[prev2] = -1;
}

void deleteFirst(int* head, int* listIndex) {
int toErase = *head;
*head = listIndex[*head];
listIndex[toErase] = -1;
}

int checkCircle(int* circle, int size) {
int idxI;
for(idxI = 1; idxI < size; ++idxI) {
if(circle[0] == circle[idxI])
return 1;
242 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
return 0;
}

int checkConsistent(int * listIndex, int size, int head) {
int idxI, validSize = 0;
int act = head;
int* circle = (int*)malloc(sizeof (int)*size);
for(idxI = 0; idxI < size; ++idxI) {
if(listIndex[idxI] != -1) {
validSize++;
}
}
if(head == -1 || validSize == 0) {
printf("List is inconsistent.\n");
return 1;
}
for (idxI = 0; idxI < validSize; ++idxI) {
if(listIndex[act] == -1) {
printf("List is inconsistent.\n");
return 1;
}
act = listIndex[act];
circle[idxI] = act;
}
for(idxI = 0; idxI < validSize; ++idxI)
if(checkCircle(&circle[idxI], validSize - idxI)) {
printf("List is inconsistent.\n");
return 1;
}
printf("List is consistent.\n");
return 0;
}
int main() {
double listData[7] = {34, 12.55, 893.2, 2, 11.6, 47.5, 45.3};
int listIndex[7] = {-1, 0, 4, 1, 6, 3, 5};
int head = 2;

deleteFirst(&head, listIndex);
if(!checkConsistent(listIndex,
sizeof(listIndex)/sizeof(listIndex[0]), head)) {
printf("list: ");
printList(head, listIndex, listData);
}
return 0;
}
4.1.3.
#include <stdio.h>
#include <stdlib.h>
const int listSize = 7;

void printList(int head, int* listIndex, double* listData, int size) {
int act = head, idxI;
printf("[");
for(idxI = 0; idxI < size; ++idxI){
printf("%4.2lf", listData[act]);
act = listIndex[act]; // next element
if (idxI != size -1)
9. Megoldsok 243
Heckl Istvn, PE www.tankonyvtar.hu
printf(", ");
}
printf("]\n");
}
int main() {
double listData[7] = {34, 12.55, 893.2, 2, 11.6, 47.5, 45.3};
int listIndex[7] = {1, 2, 3, 4, 5, 6, 0};
int head;

printf("From where should the cyclic list start? (0-6) ");
scanf("%d", &head);
printf("list: ");
printList(head, listIndex, listData,
sizeof(listData)/sizeof(listData[0]));
return 0;
}
4.2.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int listSize=5;
typedef struct {
char name[100];
int age;
int next;
} Element;

void printList(int head, Element* myList) {
int act=head;
printf("[");
while (act != -1) {
printf("(%s, %d)", myList[act].name, myList[act].age);
act = myList[act].next; // next element
if (act != -1)
printf(", ");
}
printf("]");
}

int freeSpace(int listSize, Element* myList) {
int trial;
srand(333);
do { // if list is full then this is infinite loop
trial = rand()%(listSize-1)+1;
} while (myList[trial].next != -2);
return trial;
}

void addFirst(int* head, int listSize, Element* myList) {
int oldHead= *head, newHead;
char name[100];
int age;

printf("name: ");
scanf("%s", name);
printf("age: ");
scanf("%d", &age);
newHead = freeSpace(listSize, myList);
244 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
myList[newHead].next = oldHead;
*head = newHead;
strcpy(myList[newHead].name, name);
myList[newHead].age = age;
}

int main() {
Element myList[listSize]={{ "", 0, -2}, {"", 0, -2}, {"", 0, -2},
{"", 0, -2}, {"", 0, -2}};
int head=-1; // no list

printf("list: ");
printList(head, myList);
printf("\n");
addFirst(&head, listSize, myList);
printList(head, myList);
printf("\n");
addFirst(&head, listSize, myList);
printList(head, myList);
printf("\n");
addFirst(&head, listSize, myList);
printList(head, myList);
printf("\n");
return 0;
}
4.2.2.4.2.3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct {
char name[100];
int age;
int next;
} Element;

void printList(int head, Element* myList) {
int act=head;
printf("[");
while (act != -1) {
printf("(%s, %d)", myList[act].name, myList[act].age);
act = myList[act].next; // next element
if (act != -1)
printf(", ");
}
printf("]");
}

int checkFreeSpace(int * indexArray, int listSize){
int idxI;

for(idxI = 0; idxI < listSize; ++idxI){
if(indexArray[idxI] == -2) //van mg hely
return 0;
}
return 1;
}
9. Megoldsok 245
Heckl Istvn, PE www.tankonyvtar.hu

void reAllocation(Element* myList, int* listSize) {
int idxI;
Element* myList2;
printf("Array is full, reallocating.\n");
myList2 = (Element*)malloc(sizeof(Element)*(2*(*listSize)));
for(idxI = 0; idxI < *listSize; ++idxI) {
myList2[idxI] = myList[idxI];
}
for(idxI = *listSize; idxI < (2 * (*listSize)); ++idxI) {
myList2[idxI].next = -2;
}
myList = myList2;
*listSize = 2 * (*listSize);

}

int freeSpace(int listSize, Element* myList) {
int trial, idxI;
int * indexArray;
indexArray = (int*)malloc(sizeof(int) * listSize);
for(idxI = 0; idxI < listSize; ++idxI) {
indexArray[idxI] = -2;
}
srand(time(NULL));
do { // egszen addig fut, amg res helyet nem tall, ha nincs ilyen
meghvja a reAllocation fv-t
if(checkFreeSpace(indexArray, listSize)) {
reAllocation(myList, &listSize);
indexArray = (int*)malloc(sizeof(int) * listSize);
for(idxI = 0; idxI < listSize; ++idxI) {
indexArray[idxI] = -2;
}
}
trial = rand()%(listSize);
indexArray[trial] = myList[trial].next;
} while (myList[trial].next != -2);
free(indexArray);
return trial;
}

void addLast(int* sentinel, int listSize, Element* myList) {
int newSentinel;
char name[100];
int age;

printf("name: ");
scanf("%s", name);
printf("age: ");
scanf("%d", &age);
newSentinel = freeSpace(listSize, myList);
myList[*sentinel].next = newSentinel;
myList[newSentinel].next = -1;
strcpy(myList[newSentinel].name, name);
myList[newSentinel].age = age;
*sentinel = newSentinel;
}

void addFirst(int* sentinel, int listSize, Element* myList) {
246 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int newSentinel;
char name[100];
int age;

printf("name: ");
scanf("%s", name);
printf("age: ");
scanf("%d", &age);
newSentinel = freeSpace(listSize, myList);
myList[newSentinel].next = -1;
strcpy(myList[newSentinel].name, name);
myList[newSentinel].age = age;
*sentinel = newSentinel;
}

int main() {
int idxI, listSize = 3;
int head=-1; // no list
int sentinel;

Element* myList = (Element*)malloc(sizeof(Element)*listSize);
for(idxI = 0; idxI < listSize; ++idxI) {
myList[idxI].next = -2;
}
printf("list: ");
printList(head, myList);
printf("\n");
addFirst(&head, listSize, myList);
printList(head, myList);
printf("\n");
sentinel = head;
for(idxI = 0; idxI < 11; ++idxI) {
addLast(&sentinel, listSize, myList);
printList(head, myList);
//printf("%d", myList[idxI].next);
printf("\n");
}
free(myList);
return 0;
}
4.3.1.
#include <stdio.h>
#include <malloc.h>
typedef struct le {
int data;
struct le* next;
} listElem;
void displayElement(listElem* act) {
printf("[%d, %#p]->", act->data, act->next);
}

int main() {
listElem *act=NULL, *head=NULL, elem1={12, NULL}, elem2={45, NULL},
elem3={7, NULL};

head = &elem1;
elem1.next = &elem2;
elem2.next = &elem3;
9. Megoldsok 247
Heckl Istvn, PE www.tankonyvtar.hu
elem3.next = NULL; // list finished
act = head;
printf("elements:");
displayElement(act);
act = act->next;
displayElement(act);
act = act->next;
displayElement(act);
printf("NULL");
printf("\n%9s%-#18p%-#18p%-#15p%-18s", "address:", head, head->next,
head->next->next, "");
printf("\n\n%9s%-#18p", "head:", head);
printf("\n%9s%-#18p\n\n", "address:", &head);
return 0;
}
4.3.2.
#include <stdio.h>
#include <malloc.h>
typedef struct le {
int data;
struct le* next;
struct le* prev;
} listElem;
void displayElement(listElem* act) {
printf("[%d, %#p]->", act->data, act->next);
}
void displayElement2(listElem* act) {
printf("[%d, %#p]->", act->data, act->prev);
}

int main() {
listElem *act=NULL, *head=NULL, *tail=NULL, elem1={12, NULL, NULL},
elem2={45, NULL, NULL}, elem3={7, NULL, NULL};

head = &elem1;
//head->prev = NULL;
elem1.next = &elem2;
elem1.prev = NULL;
elem2.next = &elem3;
elem2.prev = &elem1;
elem3.next = NULL; // list finished
elem3.prev = &elem2;
act = head;
printf("elements:");
displayElement(act);
act = act->next;
displayElement(act);
act = act->next;
tail = act;
displayElement(act);
printf("NULL");
printf("\n%9s%-#18p%-#18p%-#15p%-18s", "address:", head, head->next,
head->next->next, "");
printf("\n\n%9s%-#18p", "head:", head);
printf("\n%9s%-#18p\n\n", "address:", &head);

printf("Now let's see backward: \n");
displayElement2(tail);
248 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
displayElement2(tail->prev);
displayElement2(tail->prev->prev);
printf("NULL\n");
return 0;
}
4.4.1.
#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct le {
char name[100];
int price;
float power;
struct le* next;
} listElem;

listElem* createListElem() {
listElem* result=(listElem*)malloc(sizeof(listElem));
printf("name: ");
scanf("%s", result->name);
printf("price: ");
scanf("%d", &result->price);
printf("power: ");
scanf("%f", &result->power);
result->next = NULL;
return result;
}

void displayListElem(listElem* myList) {
printf("(name: %s, ", myList->name);
printf("price: %d, ", myList->price);
printf("power: %f)", myList->power);
}

void deleteList(listElem* sentinel) {
listElem *act, *prev;
act = sentinel->next;
while (act) {
prev = act;
act = act->next;
free(prev);
}
}

void listList(listElem* sentinel) {
listElem *act=sentinel->next;
printf("List elments: ");
while (act) {
displayListElem(act);
act = act->next;
if (act)
printf(",");
}
printf("\n");
}

void insertAfter(listElem* sentinel, listElem* myElem, int place) {
9. Megoldsok 249
Heckl Istvn, PE www.tankonyvtar.hu
// place=0 means insert as the first element
listElem *act=sentinel->next, *prev=sentinel;
while (place>0 && act!=NULL) {
prev = act;
act = act->next;
place--;
}
prev->next = myElem;
myElem->next = act;
}

int main() {
listElem sentinel={"", 0, 0, NULL}, *temp=NULL;
temp = createListElem();
insertAfter(&sentinel, temp, 2);
listList(&sentinel);

temp = createListElem();
insertAfter(&sentinel, temp, 2);
listList(&sentinel);

temp = createListElem();
insertAfter(&sentinel, temp, 2);
listList(&sentinel);

temp = createListElem();
insertAfter(&sentinel, temp, 2);
listList(&sentinel);
deleteList(&sentinel);
return 0;
}
4.4.2.
void deleteAt(listElem* sentinel, int place) {
// place=0 means insert as the first element
listElem *act=sentinel->next, *prev=sentinel;
place--; // listElement numbering start from 1 (sentinel is 0)
while (place>0 && act!=NULL) {
prev = act;
act = act->next;
place--;
}
if (act == NULL) return; // the same condition as: place =! 0
prev->next = act->next;
free(act); act=NULL;
}
4.4.3.
#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct le {
char name[100];
int price;
float power;
struct le* next;
} listElem;
listElem* createListElem() {
250 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
listElem* result=(listElem*)malloc(sizeof(listElem));
printf("name: ");
scanf("%s", result->name);
printf("price: ");
scanf("%d", &result->price);
printf("power: ");
scanf("%f", &result->power);
result->next = NULL;
return result;
}

void displayListElem(listElem* myList) {
printf("(name: %s, ", myList->name);
printf("price: %d, ", myList->price);
printf("power: %f)", myList->power);
}

void deleteList(listElem* sentinel) {
listElem *act, *prev;
act = sentinel->next;
while (act) {
prev = act;
act = act->next;
free(prev);
}
}

void listList(listElem* sentinel) {
listElem *act=sentinel->next;
printf("List elments: ");
while (act) {
displayListElem(act);
act = act->next;
if (act)
printf(", ");
}
printf("\n");
}

void insertAfter(listElem* sentinel, listElem* myElem, int place, int
*size) {
// place=0 means insert as the first element
listElem *act = sentinel->next, *prev = sentinel;
while (place > 0 && act != NULL) {
prev = act;
act = act->next;
place--;
}
prev->next = myElem;
myElem->next = act;
(*size)++;
}

void invertElements(listElem* sentinel, int invert_1, int invert_2) {
listElem *act, *inv1, *inv2, *temp, *prev1, *prev2, *next1, *next2,
*tempPrev, *tempNext;
int idxI;
act = inv1 = inv2 = prev1 = prev2 = next1 = next2 = tempPrev =
tempNext = NULL;
9. Megoldsok 251
Heckl Istvn, PE www.tankonyvtar.hu
act = sentinel->next;
tempPrev = sentinel;
tempNext = act->next;
for(idxI = 1; idxI <= invert_1; ++idxI) {
if (idxI == invert_1) {
inv1 = act;
prev1 = tempPrev;
next1 = tempNext;
}
else {
tempPrev = act;
act = act->next;
tempNext = act->next;
}
}
act = sentinel->next;
tempPrev = sentinel;
tempNext = act->next;
for(idxI = 1; idxI <= invert_2; ++idxI) {
if (idxI == invert_2) {
inv2 = act;
prev2 = tempPrev;
next2 = tempNext;
}
else {
tempPrev = act;
act = act->next;
tempNext = act->next;
}
}
if((invert_1 - invert_2) * (invert_1 - invert_2) == 1) {
if(invert_1 < invert_2) {
prev1->next = inv2;
inv1->next = inv2->next;
inv2->next = inv1;
}
else if(invert_2 < invert_1) {
prev2->next = inv1;
inv2->next = inv1->next;
inv1->next = inv2;
}
}
else if(inv1 != NULL && inv2 != NULL) {
prev1->next = inv2;
inv2->next = next1;
prev2->next = inv1;
inv1->next = next2;


}
else
printf("Cannot invert!\n");

}

void listFromEnd(listElem* sentinel, int size) {
listElem* act = sentinel->next;
int idxI;

252 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
for(idxI = 0; idxI < size; ++idxI) {
if(idxI == size-1) {
printf(" (name: %s, ", act->name);
printf("price: %d, ", act->price);
printf("power: %f)", act->power);
if(act == sentinel->next)
printf("\n");
else
printf(",");
listFromEnd(sentinel, size-1);

}
else
act = act->next;
}
}

void searchbyName(listElem* sentinel, int size, int searchAfter, int
searchAll, char* name) {
listElem *act = sentinel->next;
int idxI;

printf("Found:\n");
for(idxI = 0; idxI < searchAfter; ++idxI)
act = act->next;
while(act != NULL) {
if(!strcmp(act->name, name))
printf("(name: %s, price: %d, power: %f)\n", act->name, act-
>price, act->power);
if(!searchAll)
return;
else
act = act->next;
}
}

void searchbyPrice(listElem* sentinel, int size, int searchAfter, int
searchAll, int price) {
listElem *act = sentinel->next;
int idxI;

printf("Found:\n");
for(idxI = 0; idxI < searchAfter; ++idxI)
act = act->next;
while(act != NULL) {
if(act->price == price)
printf("(name: %s, price: %d, power: %f)\n", act->name, act-
>price, act->power);
if(!searchAll)
return;
else
act = act->next;
}
}

void searchbyPower(listElem* sentinel, int size, int searchAfter, int
searchAll, float power) {
listElem *act = sentinel->next;
int idxI;
9. Megoldsok 253
Heckl Istvn, PE www.tankonyvtar.hu

printf("Found:\n");
for(idxI = 0; idxI < searchAfter; ++idxI)
act = act->next;
while(act != NULL) {
if(act->power == power)
printf("(name: %s, price: %d, power: %f)\n", act->name, act-
>price, act->power);
if(!searchAll)
return;
else
act = act->next;
}
}

void deletebyName(listElem* sentinel, int* size, char* name) {
listElem *act = sentinel->next, *prev = sentinel;

while(act != NULL) {
if(!strcmp(act->name, name)) {
prev->next = act->next;
free(act);
act = prev->next;
(*size)--;
}
else {
prev = act;
act = act->next;
}
}
}

void deletebyPrice(listElem* sentinel, int* size, int price) {
listElem *act = sentinel->next, *prev = sentinel;

while(act != NULL) {
if(act->price == price) {
prev->next = act->next;
free(act);
act = prev->next;
(*size)--;
}
else {
prev = act;
act = act->next;
}
}
}

void deletebyPower(listElem* sentinel, int* size, float power) {
listElem *act = sentinel->next, *prev = sentinel;

while(act != NULL) {
if(act->power == power) {
prev->next = act->next;
free(act);
act = prev->next;
(*size)--;
}
254 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
else {
prev = act;
act = act->next;
}
}
}

int main() {
int menu, subMenu, subSubMenu, invert_1, invert_2, listSize = 0,
searhAfter, searchPrice, deletePrice, controller, controller2,
tempSearchAfter;
float searchPower, deletePower;
char searchName[50], deleteName[50];
listElem sentinel={"", 0, 0, NULL}, *temp=NULL;
temp = createListElem();
insertAfter(&sentinel, temp, 2, &listSize);
listList(&sentinel);

temp = createListElem();
insertAfter(&sentinel, temp, 2, &listSize);
listList(&sentinel);

temp = createListElem();
insertAfter(&sentinel, temp, 2, &listSize);
listList(&sentinel);

/*temp = createListElem();
insertAfter(&sentinel, temp, 2, &listSize);
listList(&sentinel);*/
for(;;) {
printf("\n***Menu***\n");
printf("1. Search\n2. Invert two elements\n3. List from the
end\n4. Delete certain element(s)\n5. Exit\n");
scanf("%d", &menu);
switch(menu) {
case 1:
controller = 0;
for(;controller == 0;) {
printf("\n***Search Menu***\n1. Search the first
occurrence\n2. Search the first occurrence after index xy\n3. Search all
occurrence\n4. Back\n");
scanf(%d, &subMenu);
switch(subMenu) {
case 1:
controller2 = 0;
for(;controller2 == 0;) {
printf("***\nSearch the first occ.
SubMenu***\n");
printf("1. Search by name\n2. Search by
price\n3. Search by power\n4. Back\n");
scanf(%d, &subSubMenu);
switch(subSubMenu) {
case 1:
controller = 1;
controller2 = 1;
printf("Search name? ");
scanf("%s", searchName);
searchbyName(&sentinel, listSize,
0, 0, searchName);
9. Megoldsok 255
Heckl Istvn, PE www.tankonyvtar.hu
break;
case 2:
controller = 1;
controller2 = 1;
printf("Search price? ");
scanf("%d", &searchPrice);
searchbyPrice(&sentinel,
listSize, 0, 0, searchPrice);
break;
case 3:
controller = 1;
controller2 = 1;
printf("Search power? ");
scanf("%f", &searchPower);
searchbyPower(&sentinel,
listSize, 0, 0, searchPower);
break;
case 4:
controller2 = 1;
break;
default:
controller2 = 0;
}
}
break;
case 2:
controller2 = 0;
for(;controller2 == 0;) {
printf("\n***Search the first occ after
index SubMenu***\n");
printf("1. Search by name\n2. Search by
price\n3. Search by power\n4. Back\n");
scanf("%d", &subSubMenu);
if(subSubMenu == 4)
break;
for(tempSearchAfter = 0; tempSearchAfter ==
0;) {
printf(After index? );
scanf("%d", &searhAfter);
if(searhAfter <= listSize)
tempSearchAfter = 1;
else
printf(Bad index!!!\n);
}
switch(subSubMenu) {
case 1:
controller = 1;
controller2 = 1;
printf("Search name? ");
scanf("%s", searchName);
searchbyName(&sentinel, listSize,
searhAfter, 0, searchName);
break;
case 2:
controller = 1;
controller2 = 1;
printf("Search price? ");
scanf("%d", &searchPrice);
256 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
searchbyPrice(&sentinel,
listSize, searhAfter, 0, searchPrice);
break;
case 3:
controller = 1;
controller2 = 1;
printf("Search power? ");
scanf("%f", &searchPower);
searchbyPower(&sentinel,
listSize, searhAfter, 0, searchPower);
break;
default:
controller2 = 0;
}
}
break;
case 3:
controller2 = 0;
for(;controller2 == 0;) {
printf("\n***Search all occ.
SubMenu***\n");
printf("1. Search by name\n2. Search by
price\n3. Search by power\n4. Back\n");
scanf("%d", &subSubMenu);
switch(subSubMenu) {
case 1:
controller = 1;
controller2 = 1;
printf("Search name? ");
scanf("%s", searchName);
searchbyName(&sentinel, listSize,
0, 1, searchName);
break;
case 2:
controller = 1;
controller2 = 1;
printf("Search price? ");
scanf("%d", &searchPrice);
searchbyPrice(&sentinel,
listSize, 0, 1, searchPrice);
break;
case 3:
controller = 1;
controller2 = 1;
printf("Search power? ");
scanf("%f", &searchPower);
searchbyPower(&sentinel,
listSize, 0, 1, searchPower);
break;
case 4:
controller2 = 1;
break;

default:
controller2 = 0;
}
}
break;
}
9. Megoldsok 257
Heckl Istvn, PE www.tankonyvtar.hu
if(subMenu == 4)
break;
}
break;
case 2:
for(;;) {
printf("\nWhich two would you like to invert? (e.g. 1
4)\n");
scanf("%d%d", &invert_1, &invert_2);
if(listSize < invert_1 || listSize < invert_2 ||
invert_1 == 0 || invert_2 == 0)
printf("Bad index(es)!!!\n");
else {
invertElements(&sentinel, invert_1, invert_2);
break;
}
}
break;
case 3:
printf("List elements: ");
listFromEnd(&sentinel, listSize);
//listList(&sentinel);
break;
case 4:
controller = 0;
for(;controller == 0;) {
printf("\n*** Delete SubMenu***\n");
printf("1. Delete by name\n2. Delete by price\n3.
Delete by power\n4. Back\n");
scanf("%d", &subMenu);
switch(subMenu) {
case 1:
printf("Delete name? ");
scanf("%s", deleteName);
deletebyName(&sentinel, &listSize,
deleteName);
controller = 1;
break;
case 2:
printf("Delete price? ");
scanf("%d", &deletePrice);
deletebyPrice(&sentinel, &listSize,
deletePrice);
controller = 1;
break;
case 3:
printf("Delete power? ");
scanf("%f", &deletePower);
deletebyPower(&sentinel, &listSize,
deletePower);
controller = 1;
break;
case 4:
controller = 1;
break;
default:
controller = 0;
}
}
258 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
break;
case 5:
return 0;

}
}
deleteList(&sentinel);
return 0;
}
4.5.1.
#include <iostream>
#include <cstring>
using namespace std;

class airplane {
public:
int id;
int passengers;
airplane(int p1=0, int p2=0) : id(p1), passengers(p2), next(0),
prev(0) {}
bool operator==(const airplane& para) const;
airplane *next, *prev;
};
ostream& operator<<(ostream& os, const airplane& para) {
os << "(id:" << para.id << ", passengers: " << para.passengers <<
")";
return os;
}

bool airplane::operator==(const airplane& para) const {
bool result=false;
if (id==para.id && passengers==para.passengers)
result=true;
return result;
}

template <typename T1>
class list {
T1 *head, *tail, *act;
int elemNum;
public:
list() : head(0), tail(0), act(0), elemNum(0) {}
~list();
T1* search(const T1& para) const; // search from head to tail
void insert(const T1& para); // before act
void delAct(); // act moves to the previous element
void moveAct(int para); // realative move from act
T1& getElem() const {return *act;}
int getElemNum() const {return elemNum;}
template <typename U1> friend ostream& operator<<(ostream&, const
list<U1>&);
};

template <typename T1>
list<T1>::~list() {
T1 *temp=head, *prev;
while (temp) {
prev=temp;
9. Megoldsok 259
Heckl Istvn, PE www.tankonyvtar.hu
temp=temp->next;
delete prev;
}
}

template <typename T1>
T1* list<T1>::search(const T1& para) const {
// search from head to tail
T1* temp=head;
while (temp) {
if (*temp==para)
return temp;
temp=temp->next;
}
return 0;
}

template <typename T1>
void list<T1>::insert(const T1& para) { // before act
elemNum++;
T1 *temp=new T1(para), *before;
if (head==0) {
head=tail=act=temp;
return;
}
before=act->prev;
if (before==0)
head=temp;
else
before->next=temp;
temp->next=act;
act->prev=temp;
temp->prev=before;
act=temp; // new act value is the inserted element
}

template <typename T1>
void list<T1>::delAct() { // at act
T1 *after, *before;
if (act==0)
return;
before=act->prev;
after=act->next;
if (before==0)
act=head=after;
else {
before->next=after;
act=before;
}
if (after==0)
tail=before;
else
after->prev=before;
elemNum--;
}

template <typename T1>
void list<T1>::moveAct(int para) {
if (para>0)
260 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
while (act->next && para) {
act=act->next;
para--;
}
else
while (act->prev && para) {
act=act->prev;
para++;
}
}

template <typename U1>
ostream& operator<< (ostream& os, const list<U1>& para) {
U1* temp=para.head;
if (!temp)
os << "empty";
while (temp) {
os << *temp << ", ";
temp=temp->next;
}
os << endl;
return os;
}

int main() {
airplane a(1, 500), b(2, 450), c(3, 220), d(4, 260);
list<airplane> myList;
cout << myList;
myList.insert(a);
cout << myList;
myList.insert(b);
cout << myList;
myList.insert(c);
cout << myList;
myList.insert(d);
cout << myList;
cout << "ElemNum:" << myList.getElemNum() << endl;
cout << "act elem: " << myList.getElem() << endl;
cout << "moveAct(2)" << endl;
myList.moveAct(2);
cout << "act elem: " << myList.getElem() << endl;
cout << "delAct()" << endl;
myList.delAct();
cout << myList;
cout << "moveAct(-2)" << endl;
myList.moveAct(-2);
cout << "act elem: " << myList.getElem() << endl;
cout << "delAct()" << endl;
myList.delAct();
cout << "act elem: " << myList.getElem() << endl;
cout << myList;
return 0;
}
4.5.2.
#include <iostream>
#include <cstring>
using namespace std;

9. Megoldsok 261
Heckl Istvn, PE www.tankonyvtar.hu
class airplane {
public:
int id;
int passengers;
airplane(int p1=0, int p2=0) : id(p1), passengers(p2), next(0),
prev(0) {}
bool operator==(const airplane& para) const;
airplane *next, *prev;
};
ostream& operator<<(ostream& os, const airplane& para) {
os << "(id:" << para.id << ", passengers: " << para.passengers <<
")";
return os;
}

bool airplane::operator==(const airplane& para) const {
bool result=false;
if (id==para.id && passengers==para.passengers)
result=true;
return result;
}

template <typename T1>
class list {
T1 *head, *tail, *act;
int elemNum;
public:
list() : head(0), tail(0), act(0), elemNum(0) {}
~list();
T1* search(const T1& para) const; // search from head to tail
void insert(const T1& para); // before act
void delAct(); // act moves to the previous element
void delAbs(int para);
void moveAct(int para); // realative move from act
void moveAbs(int para);
T1& getElem() const {return *act;}
int getElemNum() const {return elemNum;}
template <typename U1> friend ostream& operator<<(ostream&, const
list<U1>&);
};

template <typename T1>
list<T1>::~list() {
T1 *temp=head, *prev;
while (temp) {
prev=temp;
temp=temp->next;
delete prev;
}
}

template <typename T1>
T1* list<T1>::search(const T1& para) const {
// search from head to tail
T1* temp=head;
while (temp) {
if (*temp==para)
return temp;
temp=temp->next;
262 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
return 0;
}

template <typename T1>
void list<T1>::insert(const T1& para) { // before act
elemNum++;
T1 *temp=new T1(para), *before;
if (head==0) {
head=tail=act=temp;
return;
}
before=act->prev;
if (before==0)
head=temp;
else
before->next=temp;
temp->next=act;
act->prev=temp;
temp->prev=before;
act=temp; // new act value is the inserted element
}

template <typename T1>
void list<T1>::delAbs(int para) {
moveAbs(para);
delAct();
}

template <typename T1>
void list<T1>::delAct() { // at act
T1 *after, *before;
if (act==0)
return;
before=act->prev;
after=act->next;
if (before==0)
act=head=after;
else {
before->next=after;
act=before;
}
if (after==0)
tail=before;
else
after->prev=before;
elemNum--;
}

template <typename T1>
void list<T1>::moveAct(int para) {
if (para>0)
while (act->next && para) {
act=act->next;
para--;
}
else
while (act->prev && para) {
act=act->prev;
9. Megoldsok 263
Heckl Istvn, PE www.tankonyvtar.hu
para++;
}
}

template <typename T1>
void list<T1>::moveAbs(int para) {
act=head;
for (int i=para;i>0;i--) {
act=act->next;
}
}

template <typename U1>
ostream& operator<< (ostream& os, const list<U1>& para) {
U1* temp=para.head;
if (!temp)
os << "empty";
while (temp) {
os << *temp << ", ";
temp=temp->next;
}
os << endl;
return os;
}

int main() {
airplane a(1, 500), b(2, 450), c(3, 220), d(4, 260);
list<airplane> myList;
cout << myList;
myList.insert(a);
cout << myList;
myList.insert(b);
cout << myList;
myList.insert(c);
cout << myList;
myList.insert(d);
cout << myList;
cout << "ElemNum:" << myList.getElemNum() << endl;
cout << "act elem: " << myList.getElem() << endl;
cout << "moveAct(2)" << endl;
myList.moveAct(2);
cout << "act elem: " << myList.getElem() << endl;
cout << "delAct()" << endl;
myList.delAct();
cout << myList;
cout << "moveAct(-2)" << endl;
myList.moveAct(-2);
cout << "act elem: " << myList.getElem() << endl;
cout << "delAct()" << endl;
myList.delAct();
cout << "act elem: " << myList.getElem() << endl;
cout << myList;
return 0;
}
4.6.1.
#include <stdio.h>
#include <stdlib.h>

264 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
struct TElement
{
struct TElement * next;
int Data;
};

struct TList
{
struct TElement * Head;
struct TElement * Actual;
};

void InitList(struct TList * L)
{
L->Head = L->Actual = NULL;
}

// we suppose that, the actual is the last element
void Add(struct TList * L, int data)
{
if (L->Head == NULL)
L->Head = L->Actual = (struct TElement *)malloc(sizeof(struct
TElement));
else
{
L->Actual->next = (struct TElement *)malloc(sizeof(struct TElement));
L->Actual = L->Actual->next;
}
L->Actual->Data = data;
L->Actual->next = NULL;
}

void PrintList(struct TList * L)
{
if (L->Head == NULL)
return;
L->Actual = L->Head;
printf("The list: ");
while (L->Actual->next)
{
printf("%d ", L->Actual->Data);
L->Actual = L->Actual->next;
}
printf("%d\n", L->Actual->Data);
}

void FreeList(struct TList * L)
{
struct TElement * tmp;
if (L->Head == NULL)
return;
L->Actual = L->Head;
do
{
tmp = L->Actual;
L->Actual = L->Actual->next;
free(tmp);
tmp = NULL;
} while (L->Actual);
9. Megoldsok 265
Heckl Istvn, PE www.tankonyvtar.hu
}

int main()
{
struct TList List;
int num;
InitList(&List);
do
{
printf("Type a number: ");
scanf("%d", &num);
if (num != 0)
{
if (num != -1)
Add(&List, num);
else
PrintList(&List);
}
} while (num != 0);
FreeList(&List);
return 0;
}
4.7.1.
#include <stdio.h>
#include <stdlib.h>

struct PrimeArray {
int current_number;
struct PrimeArray* next;
};

void UploadPrimeArray(struct PrimeArray*, int);
void ListPrimeArray(struct PrimeArray);
void RemoveNotPrimes(struct PrimeArray*);
void FreePrimeArray(struct PrimeArray*);

int main() {
int MAX_NUMBER;
struct PrimeArray my_prime_array;

printf("Pleas enter a number, the orignal list will be generated from
2 to this number.\n");
scanf("%d", &MAX_NUMBER);
printf("The original list:\n");
UploadPrimeArray(&my_prime_array, MAX_NUMBER);
ListPrimeArray(my_prime_array);
RemoveNotPrimes(&my_prime_array);
printf("\n\nThe list, after removing not primes:\n");
ListPrimeArray(my_prime_array);
FreePrimeArray(&my_prime_array);
return 0;
}

void UploadPrimeArray(struct PrimeArray* first, int max_number) {
int i;
struct PrimeArray* actual;

actual = first;
266 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
actual->current_number = 2;
actual->next = NULL;
//ltrehozok egy lncolt listt, aminek elemei 2-tl n-ig a szmok
for (i = 3; i <= max_number; ++i) {
actual->next = (struct PrimeArray*)malloc(sizeof(struct
PrimeArray));
actual = actual->next;
actual->current_number = i;
actual->next = NULL;
}

}
void ListPrimeArray(struct PrimeArray first) {
int i = 1;
struct PrimeArray* actual = &first;

while (actual) {
printf("%3d.element: %3d\n", i++, actual->current_number);
actual = actual->next;
}

}
void RemoveNotPrimes(struct PrimeArray* first) {
struct PrimeArray* actual, *prev, *next;

//dupla ciklus, a klsvel megyek vgig a listn
while (first->next) {
actual = first->next;
prev = first;
next = actual->next;

//a bels ciklussal vizsglom az akutlis els elem utni szmok
oszthatsgt
while (actual->next) {
if ((actual->current_number % first->current_number) == 0) {
free(actual);
actual = next;
next = actual->next;
prev->next = actual;
}
else {
prev = actual;
actual = actual->next;
next = actual->next;
}
}
printf("\nInner steps (%%%d)\n", first->current_number);
ListPrimeArray(*first);
first = first->next;
}
}
void FreePrimeArray(struct PrimeArray* first) {
//a lista els eleme statikus, ezrt a msodiktl kezdve szabadtunk
fel
struct PrimeArray* actual = first->next;

while (actual) {
first = actual->next;
free(actual);
9. Megoldsok 267
Heckl Istvn, PE www.tankonyvtar.hu
actual = first;
}
}
4.8.1.
#include <stdio.h>
#include <malloc.h>

struct array {
int current_number;
struct array* next;
};

void Uploadarray(struct array*, int*, int);
void Combarrays(struct array**, struct array**);
void Listarray(struct array*);
void FreeArray(struct array*);

int main() {
struct array * head_first,* head_second;
int set_1[] = {1, 2, 4, 5, 6, 8, 9, 10, 13};
int set_2[] = {0, 2, 3, 5, 6, 7, 9, 11, 12, 13};
head_first = (struct array*)malloc(sizeof(struct array));
head_second = (struct array*)malloc(sizeof(struct array));

Uploadarray(head_first, set_1, sizeof(set_1)/sizeof(int));
Uploadarray(head_second, set_2, sizeof(set_2)/sizeof(int));
printf("First list:\n");
Listarray(head_first);
printf("\nSecond list:\n");
Listarray(head_second);
Combarrays(&head_first, &head_second);
printf("\nFirst list after creating the union of the sets:\n");
Listarray(head_first);
FreeArray(head_first);
return 0;
}

void Uploadarray(struct array* first, int* array_here, int size) {
int i;
struct array* actual;

actual = first;
actual->current_number = array_here[0];
actual->next = NULL;
for(i = 1; i < size; i++) {
actual->next = (struct array*)malloc(sizeof(struct array));
actual = actual->next;
actual->current_number = array_here[i];
actual->next = NULL;
}
}
void Combarrays(struct array** first_start, struct array** second_start)
{
struct array *first, *first_temp, *second_temp, *prev;

//megkeresi a legkisebb elemet a kt listban, ha ez a kettesben van,
akkor tltja az els lista elejt erre, persze a lista tbbi eleme
marad a rgi
268 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
if ((*first_start)->current_number > (*second_start)->current_number)
{
first_temp = *first_start;
second_temp = *second_start;
*second_start = (*second_start)->next;
(*first_start) = second_temp;
(*first_start)->next = first_temp;
}
prev = first = *first_start;

//ameddig ltezik a kt lista, tudok rajtuk sszehasonltst vgezni
while (first && (*second_start)) {
//ha kt elem megegyezik
if(first->current_number == (*second_start)->current_number) {
prev = first;
first = first->next;
second_temp = (*second_start);
(*second_start) = (*second_start)->next;
free(second_temp);
}
//ha az els lista eleme nagyobb
else if(first->current_number < (*second_start)->current_number) {
prev = first;
first = first->next;
}
//ha a msodik listban nagyobb a kvetkez elem
else if(first->current_number > (*second_start)->current_number) {
second_temp = (*second_start);
(*second_start) = (*second_start)->next;
prev->next = second_temp;
prev->next->next = first;
prev = second_temp;
}
}
//ha az els lista mr elfogyott volna, de maradt mg a msodikban
kivehet elem
if((*second_start))
first->next = (*second_start);
}
void Listarray(struct array* first) {
int i = 1;
struct array* actual = first;

while(actual) {
printf("%d.element: %d\n", i++, actual->current_number);
actual = actual->next;
}
}
void FreeArray(struct array* actual) {
struct array* temp = actual;
while(temp) {
actual = temp->next;
free(temp);
temp = actual;
}
}
4.8.2.
#include <stdio.h>
9. Megoldsok 269
Heckl Istvn, PE www.tankonyvtar.hu
#include <malloc.h>

struct array {
int current_number;
struct array* next;
};

void UploadArray(struct array*, int*, int);
void ListArray(struct array*);
void FreeArray(struct array*);
void Intersection(struct array**, struct array*);

int main() {
struct array* first, *second;
struct array** ptr_first;
int numbers_1[8] = {0,1,5,7,9,13,19,96};
int numbers_2[8] = {1,4,9,15,19,25,37,45};

first = (struct array*)malloc(sizeof(struct array));
second = (struct array*)malloc(sizeof(struct array));
ptr_first = &first;

UploadArray(first, numbers_1, 8);
UploadArray(second, numbers_2, 8);
printf("The first list:\n");
ListArray(first);
printf("\nThe second list:\n");
ListArray(second);
Intersection(ptr_first, second);
printf("\nThe first list after creating the intersecrion of the
lists:\n");
ListArray(first);
FreeArray(first);
FreeArray(second);
return 0;
}

void UploadArray(struct array* first, int* numbers, int size) {
int i;
struct array* actual = first;

for(i = 0; i < size; i++) {
if(i) {
actual->next = (struct array*)malloc(sizeof(struct array));
actual = actual->next;
}
actual->current_number = numbers[i];
actual->next = NULL;
}
}
void ListArray(struct array* first) {
int i = 1;

while(first) {
printf("%d.element: %d\n", i++, first->current_number);
first = first->next;
}
}
void FreeArray(struct array* actual) {
270 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
struct array* temp = actual;
while(temp) {
actual = temp->next;
free(temp);
temp = actual;
}
}
void Intersection(struct array** first, struct array* second) {
struct array* prev_first, *prev_second, *element_next;
//az els kzs elem megtallsig fog futni ez a ciklus, ekkor
meglesz, hogy az els listnak mi is az els eleme
while((*first) && second) {
if((*first)->current_number > second->current_number) {
prev_second = second;
second = second->next;
free(prev_second);
}
else if((*first)->current_number < second->current_number) {
prev_first = *first;
*first = (*first)->next;
free(prev_first);
}
else {
element_next = *first;
prev_first = element_next;
element_next = element_next->next;
second = second->next;
break;
}
}
//tovbbi kzs elemek keresse
while(element_next && second) {
if(element_next->current_number > second->current_number) {
second = second->next;
}
else if(element_next->current_number < second->current_number) {
prev_first->next = element_next->next;
free(element_next);
element_next = prev_first->next;
}
else {
prev_first = element_next;
element_next = element_next->next;
second = second->next;
}
}
//ha mg maradt volna elem az els lista vgn, trljk
if(element_next) {
prev_first->next = NULL;
FreeArray(element_next);
}
}
5.1.1.
#include <iostream>
using namespace std;
const int DEFAULT_STACK_SIZE=5;
class stack {
private:
9. Megoldsok 271
Heckl Istvn, PE www.tankonyvtar.hu
int elemnum, store[DEFAULT_STACK_SIZE];
bool isFull();
public:
void Init() {elemnum=0;}
bool isEmpty();
bool Push(const int n);
bool Pop(int &n);
};

bool stack::isFull() {
return elemnum==DEFAULT_STACK_SIZE;
}
bool stack::isEmpty() {
return elemnum==0;
}
bool stack::Push(const int n) {
if (isFull()) return false;
store[elemnum++]=n;
return true;
}
bool stack::Pop(int &n) {
if (isEmpty()) return false;
n=store[--elemnum];
return true;
}

int main() {
stack *s=new stack;
s->Init();
char c; int n;
do {
cout<<"(p)ush\np(o)p\n(e)xit\n";
cout<<"Enter your selection : ";
cin>>c;
if (c=='p') {
cout<<"Enter a number: ";
cin>>n;
if (s->Push(n)) cout<<"OK!\n";
}
if (c=='o') {
if (s->Pop(n)) cout<<n<<'\n';
}
} while (c!='e');
delete s;
return 0;
}
5.1.2.
#include <iostream>
using namespace std;
const int DEFAULT_SIZE=1;
class stack {
private:
int elemnum, *store, size;
bool isFull();
public:
void Init() {elemnum=0; store=new int[DEFAULT_SIZE];
size=DEFAULT_SIZE; }
void increaseSize() {
272 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
size*=2;
cout << "increasing size -> " << size << endl;
int* temp=new int[size];
for (int i=0;i<elemnum;i++) {
temp[i]=store[i];
}
delete[] store;
store=temp;
}
bool isEmpty();
bool Push(const int n);
bool Pop(int &n);
};

bool stack::isFull() {
return elemnum==size;
}
bool stack::isEmpty() {
return elemnum==0;
}
bool stack::Push(const int n) {
store[elemnum++]=n;
if (elemnum==size) { increaseSize(); }
return true;
}
bool stack::Pop(int &n) {
if (isEmpty()) return false;
n=store[--elemnum];
return true;
}

int main() {
stack *s=new stack;
s->Init();
char c; int n;
do {
cout<<"(p)ush\np(o)p\n(e)xit\n";
cout<<"Enter your selection : ";
cin>>c;
if (c=='p') {
cout<<"Enter a number:";
cin>>n;
if (s->Push(n)) cout<<"OK!\n";
}
if (c=='o') {
if (s->Pop(n)) cout<<n<<'\n';
}
} while (c!='e');
delete s;
return 0;
}
5.2.1.
#include <stdio.h>
#include <stdlib.h>

struct TElement
{
struct TElement * prev;
9. Megoldsok 273
Heckl Istvn, PE www.tankonyvtar.hu
int Value;
};

struct TStack
{
struct TElement * Head;
int Count;
};

void InitStack(struct TStack * S)
{
S->Head = NULL;
S->Count = 0;
}

void Push(struct TStack * S, int A)
{
struct TElement * Element = (struct TElement *)malloc(sizeof(struct
TElement));
Element->Value = A;
if (S->Head == NULL)
{
Element->prev = NULL;
S->Head = Element;
} else
{
Element->prev = S->Head;
S->Head = Element;
}
S->Count++;
}

int Pop(struct TStack * S)
{
int res = 0;
if (S->Head != NULL)
{
struct TElement * E = S->Head;
res = E->Value;
S->Head = E->prev;
free(E);
E = NULL;
S->Count--;
}
return res;
}

void FreeStack(struct TStack * S)
{
while (S->Head != NULL)
Pop(S);
}

int main(int argc, char * argv[])
{
int num;
struct TStack Stack;
InitStack(&Stack);
do
274 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
{
printf("Type a number: ");
scanf("%d", &num);
if (num != 0)
Push(&Stack, num);
} while (num != 0);
while (Stack.Count)
printf("%d\n", Pop(&Stack));
FreeStack(&Stack);
return 0;
}
5.3.1.
#include <stdio.h>
#include <stdlib.h>

struct TElement
{
struct TElement * next;
int Value;
};

struct TQueue
{
struct TElement * Head;
struct TElement * Last;
int Count;
};

void InitQueue(struct TQueue * Q)
{
Q->Head = NULL;
Q->Last = NULL;
Q->Count = 0;
}

void Push(struct TQueue * Q, int A)
{
struct TElement * Element = (struct TElement *)malloc(sizeof(struct
TElement));
Element->Value = A;
Element->next = NULL;
if (Q->Head == NULL)
{
Q->Head = Element;
Q->Last = Element;
} else
{
Q->Last->next = Element;
Q->Last = Element;
}
Q->Count++;
}

int Pop(struct TQueue * Q)
{
int res = 0;
if (Q->Head != NULL)
{
9. Megoldsok 275
Heckl Istvn, PE www.tankonyvtar.hu
struct TElement * E = Q->Head;
res = E->Value;
Q->Head = E->next;
free(E);
E = NULL;
Q->Count--;
}
return res;
}

void FreeQueue(struct TQueue * Q)
{
while (Q->Head != NULL)
Pop(Q);
}

int main(int argc, char * argv[])
{
int num;
struct TQueue Queue;
InitQueue(&Queue);
do
{
printf("Type a number: ");
scanf("%d", &num);
if (num != 0)
Push(&Queue, num);
} while (num != 0);
while (Queue.Count)
printf("%d\n", Pop(&Queue));
FreeQueue(&Queue);
return 0;
}
5.4.1.
#include <stdio.h>
#include <stdlib.h>

typedef struct Verem {
struct Verem * kovetkezo;
int adat;
} Verem;

void verembe(Verem ** verem, int adat) {
Verem * uj = (Verem*)malloc(sizeof(Verem));
uj->adat = adat;
uj->kovetkezo = *verem;
*verem = uj;
}

int verembol(Verem ** verem) {
if (*verem == NULL) {
return 0;
}
int adat = (*verem)->adat;
Verem * kovetkezo = (*verem)->kovetkezo;
free(*verem);
*verem = kovetkezo;
return adat;
276 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}

int main() {
const char * kifejezes[] = {"2", "5", "+", "3", "*", "9", "2", "1",
"+", "/", "-"};
Verem * verem = NULL;
int index;
int meret = sizeof(kifejezes) / sizeof(const char*);
for (index = 0; index < meret; index++) {
if (kifejezes[index][0] == '+') {
int a = verembol(&verem);
int b = verembol(&verem);
verembe(&verem, a + b);
} else if (kifejezes[index][0] == '-') {
int a = verembol(&verem);
int b = verembol(&verem);
verembe(&verem, b - a);
} else if (kifejezes[index][0] == '*') {
int a = verembol(&verem);
int b = verembol(&verem);
verembe(&verem, a * b);
} else if (kifejezes[index][0] == '/') {
int a = verembol(&verem);
int b = verembol(&verem);
verembe(&verem, b / a);
} else {
verembe(&verem, atoi(kifejezes[index]));
}
}
int eredmeny = verembol(&verem);
printf("Az eredmeny: %d\n", eredmeny);
return EXIT_SUCCESS;
}
5.5.1.-5.5.2.
#include <stdio.h>
#include <stdlib.h>

typedef struct Sor {
struct Sor * kovetkezo;
int adat;
} Sor;

void sorba(Sor ** sor, int adat) {
Sor * uj = (Sor*) malloc(sizeof (Sor));
uj->adat = adat;
uj->kovetkezo = NULL;
if (*sor == NULL) {
*sor = uj;
return;
}
Sor * temp = *sor;
while (temp->kovetkezo != NULL) {
temp = temp->kovetkezo;
}
temp->kovetkezo = uj;
}

int sorbol(Sor ** sor) {
9. Megoldsok 277
Heckl Istvn, PE www.tankonyvtar.hu
if (*sor == NULL) {
return 0;
}
int adat = (*sor)->adat;
Sor * kovetkezo = (*sor)->kovetkezo;
free(*sor);
*sor = kovetkezo;
return adat;
}

void ujAzonosito(Sor ** sor) {
int azonosito;
Sor * temp;
do {
azonosito = rand() % 1000;
temp = *sor;
while (temp != NULL && temp->adat != azonosito) {
temp = temp->kovetkezo;
}
} while (temp != NULL);
printf("Uj azonosito: %d\n", azonosito);
sorba(sor, azonosito);
}

void nKivesz(Sor ** sor, int n) {
int index;
for (index = 0; index < n && *sor != NULL; index++) {
printf("Az %d. azonosito: %d\n", index + 1, sorbol(sor));
}
}

int main() {
Sor * sor = NULL;
int menu;
do {
printf("Beszuras: 1\n");
printf("Kivesz: 2\n");
printf("Tobbet kivesz: 3\n");
printf("Kilepes: 4\n");
scanf("%d", &menu);
if (menu == 1) {
ujAzonosito(&sor);
}
if (menu == 2) {
if (sor != NULL)
printf("A kovetkezo azonosito: %d\n", sorbol(&sor));
else
printf("Nincs tobb varakozo!\n");
}
if (menu == 3) {
int mennyi;
printf("Mennyi azonositot szedjunk ki? ");
scanf("%d", &mennyi);
nKivesz(&sor, mennyi);
}
} while (menu != 4);
while (sor != NULL) {
sorbol(&sor);
}
278 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

return EXIT_SUCCESS;
}
5.6.1.-5.6.2.
#include <stdio.h>
#include <stdlib.h>

typedef enum Rang {
PROFESSZOR, DOCENS, ADJUNKTUS, TANARSEGED
} Rang;

typedef struct Sor {
struct Sor * kovetkezo;
int adat;
Rang rang;
} Sor;

void beszuras(Sor ** sor, int adat, Rang rang) {
Sor * uj = (Sor*) malloc(sizeof (Sor));
uj->adat = adat;
uj->rang = rang;
uj->kovetkezo = NULL;
if (*sor == NULL) {
*sor = uj;
return;
}
Sor * temp = *sor;
Sor * prev = NULL;
while (temp != NULL && temp->rang <= rang) {
prev = temp;
temp = temp->kovetkezo;
}
uj->kovetkezo = temp;
if (prev == NULL) {
*sor = uj;
} else {
prev->kovetkezo = uj;
}
//uj->kovetkezo = temp->kovetkezo;
//temp->kovetkezo = uj;
}

int kovetkezo(Sor ** sor) {
if (*sor == NULL) {
return 0;
}
int adat = (*sor)->adat;
Sor * kovetkezo = (*sor)->kovetkezo;
free(*sor);
*sor = kovetkezo;
return adat;
}

void megjelenit(Sor * sor) {
while (sor != NULL) {
printf("Azonosito: %d\trang: ", sor->adat);
switch (sor->rang) {
case PROFESSZOR:
9. Megoldsok 279
Heckl Istvn, PE www.tankonyvtar.hu
printf("professzor\n");
break;
case DOCENS:
printf("docens\n");
break;
case ADJUNKTUS:
printf("adjunktus\n");
break;
case TANARSEGED:
printf("tanarseged\n");
}
sor = sor->kovetkezo;
}
}

int main() {
Sor * sor = NULL;
int menu;
do {
printf("Beszuras: 1\n");
printf("Kivesz: 2\n");
printf("Kilepes: 3\n");
scanf("%d", &menu);
if (menu == 1) {
char kod[20];
int azonosito;
printf("Kerem a dokumentum azonositojat: ");
scanf("%d", &azonosito);
printf("Szemelyi kod: ");
scanf("%s", kod);
// P: professzr
// D: docens
// A: adjunktus
// T: tanarseged
switch (kod[0]) {
case 'P':
beszuras(&sor, azonosito, PROFESSZOR);
break;
case 'D':
beszuras(&sor, azonosito, DOCENS);
break;
case 'A':
beszuras(&sor, azonosito, ADJUNKTUS);
break;
case 'T':
beszuras(&sor, azonosito, TANARSEGED);
break;
default:
printf("Hibas azonosito!\n");
}
if (sor != NULL && rand() % 100 >= 55) {
printf("Elkeszult egy nyomtatas, azonositoja: %d\n\n",
kovetkezo(&sor));
}
megjelenit(sor);
}
if (menu == 2) {
if (sor != NULL) {
printf("A kovetkezo azonosito: %d\n", kovetkezo(&sor));
280 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
} else {
printf("Nincs tobb dokumentum!\n");
}
}
} while (menu != 3);
while (sor != NULL) {
kovetkezo(&sor);
}
return EXIT_SUCCESS;
}
5.7.1.
#include <stdio.h>
#include <stdlib.h>

struct row {
int value;
struct row *next;
struct row *prev;
struct row *end;
struct row *first;
};

typedef struct row row;

void NewElement(int, row*);
int ElementOut(row*);

int main() {
//kt sor lesz, az elsben troljuk az aktulis sort a Pascal
hromszgnek, a msodikban az sszes sort troljuk
row row1, row2;
int max_level, current_level;
//segdvltozk
int i, k, x, y;

row1.first = NULL;
row1.end = NULL;
row1.prev = NULL;
row1.next = NULL;
row2.first = NULL;
row2.end = NULL;
row2.prev = NULL;
row2.next = NULL;

printf("How many level do you want to crate in the Pascal's
triangle?: ");
scanf("%d", &max_level);
printf("Representing the triangle is nice only before the 13(th)
row.\n");

for (i = 0; i < max_level; i++) {
for (current_level = 0; current_level <= i; current_level++) {
if (current_level == 0) {
NewElement(1, &row1);
NewElement(1, &row2);
}
else {
if (current_level != i) {
9. Megoldsok 281
Heckl Istvn, PE www.tankonyvtar.hu
x = ElementOut(&row1);
y = row1.end->value;
NewElement(x + y, &row1);
NewElement(x + y, &row2);
}
else {
x = ElementOut(&row1);
NewElement(x, &row1);
NewElement(x, &row2);
}
}
}
}

for (i = 0; i <= max_level; i++) {
for (k = max_level; k > i; --k)
printf(" ");
for (current_level = 0; current_level < i; current_level++) {
printf("%3d ", ElementOut(&row2));
}
printf("\n");
}
return 0;
}

void NewElement(int new_value, row *s) {
row* actual;

//els elem behelyezse a sorba
if (s->first == NULL) {
actual = (row*) malloc(sizeof (row));
if (!actual)
printf("The actual element wasn't created\n");
actual->next = NULL;
actual->prev = NULL;
actual->value = new_value;
s->first = actual;
s->end = actual;
}
//tovbbi elemek elhelyezse a sorban
else {
actual = (row*) malloc(sizeof (row));
if (!actual)
printf("The actual element wasn't created\n");
actual->value = new_value;
actual->next = s->first;
actual->prev = NULL;
s->first->prev = actual;
s->first = actual;
}
}
int ElementOut(row *s) {
row *temp;
int value = 0;

if (s->end != NULL) {
value = s->end->value;
if (s->end->prev != NULL) {
temp = s->end->prev;
282 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
else {
temp = NULL;
s->first = NULL;
}
free(s->end);
s->end = temp;
}
return value;
}
5.8.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct row {
char value[20];
struct row* next;
struct row* prev;
};

void UploadFIFO(char*, char*, struct row**, struct row**);
void InsertElement(char*, struct row**, struct row**);
void List_Check_Remove(char*, struct row**);
char* Check(char*, char*);

int main() {
struct row* first = NULL, *end = NULL;
char signal[2000] =
"abcdefg#abcdefg#abfdgcdefg#abdfcdefg#abcdfdefg#abcdefg#adfcvbcdefg#abcde
fg#abcdefg#aega";
char pattern[20] = "abcdefg";

printf("Recived signal:\n%s\n", signal);
printf("\nChecking recived signal, the sequence pattern is: %s\n",
pattern);
printf("Recived expressions between ## tags:\n");

UploadFIFO(pattern, signal, &first, &end);
List_Check_Remove(pattern, &first);
return 0;
}

void UploadFIFO(char* pattern, char* signal, struct row** first, struct
row** end) {
int i = 0, k;
char temp[20];

//csak akkor kezdi el az aktulis ciklust, ha mg nincs vge az
adsnak
while (signal[i] != '\0') {
//ne rakjuk bele a mintkba a '#' karaktert
if (signal[i] != '#') {
temp[0] = signal[i];
//ha esetleg egy szekvencia kzben lenne vge az adsnak
for (k = 1; (signal[i + k] != '#'); ++k) {
if (signal[i + k] == '\0')
break;
9. Megoldsok 283
Heckl Istvn, PE www.tankonyvtar.hu
temp[k] = signal[i + k];
}
//lezrjuk a stringet
temp[k] = '\0';
InsertElement(temp, first, end);
i = i + k;
}
++i;
}
}
void InsertElement(char* temp, struct row** first, struct row **end) {
if (!(*first)) {
(*first) = (struct row*)malloc(sizeof (struct row));
(*end) = (*first);
(*first)->prev = NULL;
(*first)->next = NULL;
strcpy((*first)->value, temp);
}
else {
(*end)->next = (struct row*)malloc(sizeof (struct row));
strcpy((*end)->next->value, temp);
(*end)->next->next = NULL;
(*end)->next->prev = (*end);
(*end) = (*end)->next;
}
}
void List_Check_Remove(char* pattern, struct row** first) {
int i = 1;
struct row* actual = (*first);

while (*first) {
printf("%4d. %s-> %s\n",i++, (*first)->value, Check(pattern,
(*first)->value));
actual = (*first);
(*first) = (*first)->next;
free(actual);
}
}
char* Check(char* pattern, char* temp) {
if (strcmp(pattern, temp))
return "Wrong";
else
return "OK";
}
5.9.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct stack {
int index;
struct stack* next;
struct stack* prev;
};
int CheckExpression(char*,struct stack**);
void InsertElement(struct stack**, int);
void RemoveElement(struct stack**, int);

284 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int main() {
int check;
struct stack* end = NULL;
char expression[100];

printf("Please enter an expression e.g: (a(b(c((d))#))\n");
scanf("%s", expression);
check = CheckExpression(expression, &end);
if (check > 0)
printf("Wrong syntax!!! Too few close pharentheses!!!\n");
else if (check < 0)
printf("Wrong syntax!!! Cannot be read correctly, too many close
pharentheses!!!\n");
else
printf("Everything's all right, syntax OK.\n");
return 0;
}

int CheckExpression(char* expr, struct stack** end) {
int i, i_parentheses = 0;

for (i = 0; i < strlen(expr); ++i) {
if (expr[i] == '(') {
InsertElement(end, i_parentheses++);
}
else if (expr[i] == ')') {
if (i_parentheses == 0)
return -1;
else
RemoveElement(end, i_parentheses--);
}
}
return i_parentheses;
}
void InsertElement(struct stack** end, int index) {
if (!(*end)) {
(*end) = (struct stack*)malloc(sizeof (struct stack));
(*end)->next = NULL;
(*end)->prev = NULL;
(*end)->index = index;
}
else {
(*end)->next = (struct stack*)malloc(sizeof (struct stack));
(*end)->next->prev = (*end);
(*end) = (*end)->next;
(*end)->next = NULL;
(*end)->index = index;
}
printf("%d ->\n", (*end)->index);
}
void RemoveElement(struct stack** end, int index) {
if (*end) {
printf("<- %d\n", (*end)->index);
if ((*end)->prev) {
(*end) = (*end)->prev;
free((*end)->next);
(*end)->next = NULL;
}
else
9. Megoldsok 285
Heckl Istvn, PE www.tankonyvtar.hu
free(*end);
}
}
6.1.1.
#include <stdio.h>
struct nodeType {
int data;
nodeType *left, *right, *parent;
};
typedef struct nodeType node;

void printNode(node* act) {
printf("Act node: data: %d. ", act->data);
printf("You can go left: %d, ", act->left?1:0 );
printf("right: %d, ", act->right?1:0 );
printf("parent: %d\n", act->parent?1:0 );
}

int select() {
int result;
printf("\nLeft - 1\n");
printf("Right - 2\n");
printf("Back - 3\n");
printf("Quick - 4\n");
printf("Your choice: ");
scanf("%d", &result);
return result;
}

int main() {
node a={2, NULL, NULL, NULL}, b={11, NULL, NULL, NULL}, c={23, NULL,
NULL, NULL}, d={13, NULL, NULL, NULL},
e={9, NULL, NULL, NULL}, f={7, NULL, NULL, NULL}, g={66, NULL, NULL,
NULL}, h={8, NULL, NULL, NULL},
*root=&a, *act=root;
int choice;

a.left = &b;
a.right = &c;
b.left = &d;
b.right = &e;
b.parent = &a;
d.right = &g;
d.parent = &b;
g.parent = &d;
c.right = &f;
c.parent = &a;
f.left = &h;
h.parent = &f;

do {
printNode(act);
choice = select();
switch (choice) {
case 1:
if (act->left) act = act->left;
break;
case 2:
286 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
if (act->right) act = act->right;
break;
case 3:
if (act->parent) act = act->parent;
break;
}
} while (choice != 4);
return 0;
}
6.1.2.
#include <stdio.h>
struct nodeType {
int data;
float data2;
char string[50];
struct nodeType *left, *right, *parent;
};
typedef struct nodeType node;

void printNode(node* act) {
printf("Act node - data(int): %d, data(float): %f, data(string):
%s\n",
act->data,act->data2,act->string);
printf("You can go left: %d, ", act->left?1:0 );
printf("right: %d, ", act->right?1:0 );
printf("parent: %d\n", act->parent?1:0 );
}

void editNode(node* act) {
printf("editing node\n");
printf("data (int): ");
scanf("%d",&(act->data));
printf("data (float): ");
scanf("%f",&(act->data2));
printf("data (string): ");
scanf("%s",act->string);
}

int select() {
int result;
printf("\nLeft - 1\n");
printf("Right - 2\n");
printf("Back - 3\n");
printf("Edit - 4\n");
printf("Quit - 5\n");
printf("Your choice: ");
scanf("%d", &result);
return result;
}

int main() {
node a={2, 0.2, "", NULL, NULL, NULL}, b={11, 0.11, "", NULL, NULL,
NULL},
c={23, 0.23, "", NULL, NULL, NULL}, d={13, 0.13, "", NULL, NULL,
NULL},
e={9, 0.9, "", NULL, NULL, NULL}, f={7, 0.7, "", NULL, NULL, NULL},
g={66, 0.66, "", NULL, NULL, NULL}, h={8, 0.8, "", NULL, NULL, NULL},
*root=&a, *act=root;
9. Megoldsok 287
Heckl Istvn, PE www.tankonyvtar.hu
int choice;

a.left = &b;
a.right = &c;
b.left = &d;
b.right = &e;
b.parent = &a;
d.right = &g;
d.parent = &b;
g.parent = &d;
c.right = &f;
c.parent = &a;
f.left = &h;
h.parent = &f;

do {
printNode(act);
choice = select();
switch (choice) {
case 1:
if (act->left) act = act->left;
break;
case 2:
if (act->right) act = act->right;
break;
case 3:
if (act->parent) act = act->parent;
break;
case 4:
editNode(act);
break;
}
} while (choice != 5);
return 0;
}
6.2.1.
#include <stdio.h>
struct nodeType {
int data;
nodeType *left, *right;
};
typedef struct nodeType node;

void preOrder(node* act) {
if (!act) return;
printf("%d ", act->data);
preOrder(act->left);
preOrder(act->right);
}

void inOrder(node* act) {
if (!act) return;
inOrder(act->left);
printf("%d ", act->data);
inOrder(act->right);
}

void postOrder(node* act) {
288 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
if (!act) return;
postOrder(act->left);
postOrder(act->right);
printf("%d ", act->data);
}

int main() {
node a={1, NULL, NULL}, b={2, NULL, NULL}, c={3, NULL, NULL}, d={4,
NULL, NULL},
e={5, NULL, NULL}, f={7, NULL, NULL}, g={8, NULL, NULL}, h={9, NULL,
NULL},
*root=&b;

b.left = &f;
b.right = &c;
f.left = &d;
f.right = &h;
d.left = &a;
d.right = &e;
h.right = &g;
printf("\nPre order: ");
preOrder(root);
printf("\nIn order: ");
inOrder(root);
printf("\nPost order: ");
postOrder(root);

return 0;
}
6.3.1.
#include <stdio.h>
#include <malloc.h>
#include <limits.h>
#include <string.h>

struct nodeType {
int price;
char manufacturer[50];
unsigned int infra : 1;
float range;
struct nodeType *less, *bigger;
};
typedef struct nodeType node;

void printNode(node* act) {
printf("\n(price: %d, ", act->price);
printf("manufacturer: %s, ", act->manufacturer);
printf("infra: %d, ", act->infra);
printf("range: %3.1f) ", act->range);
}

void printTree(node* act) {
if (!act) return;
printTree(act->less);
printNode(act);
printTree(act->bigger);
}

9. Megoldsok 289
Heckl Istvn, PE www.tankonyvtar.hu
void freeTree(node* act) {
if (!act) return;
freeTree(act->less);
freeTree(act->bigger);
free(act);
}

void insertNode(node* sentinel, node* origNode) {
node *act = sentinel, *newNode;
newNode = (node*)malloc(sizeof(node));
*newNode = *origNode;
newNode->less = NULL;
newNode->bigger = NULL;
// because the sentinel we don't have to check insert as root
while (1) {
if (newNode->price <= act->price) { // if sentinel holds max key,
then equal elements must go to the left (sentinel can have only one
child)
if (act->less == NULL) {
act->less = newNode;
return;
} else act = act->less;
} else {
if (act->bigger == NULL) {
act->bigger = newNode;
return;
}
else act = act->bigger;
}
} // while end
}

int main() {
node sentinel={LONG_MAX, "", 0, 0, NULL, NULL}, myNode={25, "ibm", 0,
5.2, NULL, NULL};
insertNode(&sentinel, &myNode);
printf("\nOrdered node list: ");
myNode.price = 63;
strcpy(myNode.manufacturer, "ms");
myNode.infra=1;
myNode.range=2.1;
insertNode(&sentinel, &myNode);
myNode.price = 11;
strcpy(myNode.manufacturer, "genius");
myNode.infra=1; myNode.range=4.5;
insertNode(&sentinel, &myNode);
myNode.price = 22;
strcpy(myNode.manufacturer, "takamaka");
myNode.infra=0;
myNode.range=0.9;
insertNode(&sentinel, &myNode);
printTree(sentinel.less); // sentinel must not be printed
freeTree(sentinel.less); // sentinel must not be deleted
return 0;
}
6.3.2.
#include <stdio.h>
#include <malloc.h>
290 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
#include <limits.h>
#include <string.h>

typedef struct nodeType {
int price;
char manufacturer[50];
unsigned int infra : 1;
float range;
struct nodeType *less, *bigger, *parent;
} node;

void printNode(node* act) {
printf("(price: %d, ", act->price);
printf("manufacturer: %s, ", act->manufacturer);
printf("infra: %d, ", act->infra);
printf("range: %3.1f)\n", act->range);
}

void printTree(node* act) {
if (!act) return;
printTree(act->less);
printNode(act);
printTree(act->bigger);
}

void freeTree(node* act) {
if (!act) return;
freeTree(act->less);
freeTree(act->bigger);
free(act);
}

void insertNode(node* root, node* orig) {
node* act=root;
node* step=root;
while (step!=NULL) {
if (act->price >= orig->price) {
step=(act->less);
} else {
step=(act->bigger);
}
if (step!=NULL) { act=step; }
}
if (act->price>=orig->price) {
act->less=orig;
} else { act->bigger=orig; }
orig->parent=act;
}

int main() {
node first = {25, "ibm", 0, 5.2, NULL, NULL};
node myNode1 = {0,"",0,0.0,NULL,NULL};
node myNode2 = {0,"",0,0.0,NULL,NULL};
node myNode3 = {0,"",0,0.0,NULL,NULL};
node *root = &first;
myNode1.price = 63;
strcpy(myNode1.manufacturer, "ms");
myNode1.infra=1;
myNode1.range=2.1;
9. Megoldsok 291
Heckl Istvn, PE www.tankonyvtar.hu
insertNode(root, &myNode1);
myNode2.price = 11;
strcpy(myNode2.manufacturer, "genius");
myNode2.infra=1; myNode2.range=4.5;
insertNode(root, &myNode2);
myNode3.price = 22;
strcpy(myNode3.manufacturer, "takamaka");
myNode3.infra=0;
myNode3.range=0.9;
insertNode(root, &myNode3);
printf("Ordered node list:\n");
printTree(root); // sentinel must not be printed
return 0;
}
6.4.1.
struct TPerson
{
char Name[NAMELENGTH];
int Born, Died;
int ChildrenNum;
struct TPerson * Children;
};

void ReadPerson(FILE * fd, struct TPerson * Head)
{
int i;
fscanf(fd, "%s", Head->Name);
fscanf(fd, "%d %d %d", &Head->Born, &Head->Died, &Head-
>ChildrenNum);
Head->Children = (struct TPerson*)malloc( sizeof(struct TPerson) *
Head->ChildrenNum);
for (i = 0; i < Head->ChildrenNum; i++)
{
ReadPerson(fd, &Head->Children[i]);
}
}

int PrintChildren(struct TPerson * Head, char * name, int year)
{
int i;
int exist = FALSE;
if ( strcmp(Head->Name, name) == 0 )
{
exist = TRUE;
if (Head->ChildrenNum > 0)
{
for (i = 0; i < Head->ChildrenNum; i++)
{
if (Head->Children[i].Died != -1)
{
printf("%s, lived for ", Head->Children[i].Name);
printf("%d years\n", Head->Children[i].Died - Head-
>Children[i].Born);
} else
{
printf("%s, ", Head->Children[i].Name);
printf("%d years old\n", year - Head->Children[i].Born);
}
292 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
} else printf("%s hasn't got children!\n", name);

} else
{
for (i = 0; i < Head->ChildrenNum; i++)
{
if (!exist)
exist = PrintChildren(&Head->Children[i], name, year);
else
PrintChildren(&Head->Children[i], name, year);
}
}
return exist;
}

void FreeFamilyTree(struct TPerson * Head)
{
int i;
for (i = 0; i < Head->ChildrenNum; i++)
{
FreeFamilyTree( &Head->Children[i] );
}
free(Head->Children);
Head->Children = NULL;
}

int main(int argc, char *argv[])
{
struct TPerson Head;
char Name[NAMELENGTH];
FILE * fd = fopen(INPUT_FILE, "r");
if (fd==NULL)
{
perror("Hiba");
return 0;
}
ReadPerson(fd, &Head);
fclose(fd);

printf("Name: ");
scanf("%s", Name);
printf("Children of %s:\n*********************************\n", Name);
if ( !PrintChildren(&Head, Name, ACTUAL_YEAR ) )
printf("There is no person with name %s!\n", Name);

FreeFamilyTree(&Head);
return 0;
}
6.5.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INPUT_FILE "expr1.txt"
#define MAXLENGTH 15
#define ELEMENTNUM(a) (( a ) * 2 - 1)

9. Megoldsok 293
Heckl Istvn, PE www.tankonyvtar.hu
typedef char TElement[MAXLENGTH];

struct TExpression
{
int operandsnum;
TElement * expr;
};

void PrintExpression(struct TExpression * E)
{
int i;
for (i = 0; i < ELEMENTNUM(E->operandsnum); i++)
printf("%s ", E->expr[i]);
}

void MulDiv(struct TExpression * E)
{
int i, j;
int offs;
double a;
for (i = 0; i < ELEMENTNUM(E->operandsnum); i++)
{
offs = 0;
if (strcmp(E->expr[i], "*") == 0)
{
a = atof(E->expr[i - 1]);
a *= atof(E->expr[i + 1]);
sprintf(E->expr[i - 1], "%g", a);
offs = 1;
}
if (strcmp(E->expr[i], "/") == 0)
{
a = atof(E->expr[i - 1]);
a /= atof(E->expr[i + 1]);
sprintf(E->expr[i - 1], "%g", a);
offs = 1;
}
if (offs)
{
for (j = i; j < (ELEMENTNUM(E->operandsnum) - 2); j++)
strcpy(E->expr[j], E->expr[j + 2]);
E->operandsnum--;
i--;
}
}
}

void AddSub(struct TExpression * E)
{
int i, j;
int offs;
double a;
for (i = 0; i < ELEMENTNUM(E->operandsnum); i++)
{
offs = 0;
if (strcmp(E->expr[i], "+") == 0)
{
a = atof(E->expr[i - 1]);
a += atof(E->expr[i + 1]);
294 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
sprintf(E->expr[i - 1], "%g", a);
offs = 1;
}
if (strcmp(E->expr[i], "-") == 0)
{
a = atof(E->expr[i - 1]);
a -= atof(E->expr[i + 1]);
sprintf(E->expr[i - 1], "%g", a);
offs = 1;
}
if (offs)
{
for (j = i; j < (ELEMENTNUM(E->operandsnum) - 2); j++)
strcpy(E->expr[j], E->expr[j + 2]);
E->operandsnum--;
i--;
}
}
}

double GetValue(struct TExpression * E)
{

MulDiv(E);
AddSub(E);
return atof(E->expr[0]);
}

void ReadExpression(FILE * fd, struct TExpression * E)
{
int i;
fscanf(fd, "%d", &E->operandsnum);
E->expr = (TElement *)malloc(sizeof(TElement) * ELEMENTNUM(E-
>operandsnum));
for (i = 0; i < ELEMENTNUM(E->operandsnum) ; i++)
{
fscanf(fd, "%s", *(E->expr + i));
}
}

void FreeExpression(struct TExpression * E)
{
free(E->expr);
E->expr = NULL;
E->operandsnum = 0;
}

int main(int argc, char * argv[])
{
struct TExpression Expr;
FILE * fd = fopen(argc > 1 ? argv[1] : INPUT_FILE, "r");
if (fd == NULL)
{
perror("Error");
return 1;
}
ReadExpression(fd, &Expr);
fclose(fd);
PrintExpression(&Expr);
9. Megoldsok 295
Heckl Istvn, PE www.tankonyvtar.hu
printf(" = %g\n", GetValue(&Expr));
FreeExpression(&Expr);
return 0;
}
6.6.1.-6.6.3.
#include <stdio.h>
#include <stdlib.h>

struct binary_tree {
int number;
struct binary_tree* left;
struct binary_tree* right;
};

void Insert(struct binary_tree*, int);
void List(struct binary_tree*);
int CountNode(struct binary_tree*);
int CountLeaf(struct binary_tree*);
int MaxDepth(struct binary_tree*);
int MaxKey(struct binary_tree*);
int MinDepth(struct binary_tree*);
int SameTree(struct binary_tree*, struct binary_tree*);

int main() {
struct binary_tree* head = NULL, *head2 = NULL;
int i;
int tree_1[] = {7, 9, 13, 15, 45, 2, 1, 5, 94};
int tree_2[] = {7, 9, 13, 15, 45, 2, 1, 5, 94};

for (i = 0; i < sizeof(tree_1)/sizeof(int); ++i) {
//els elem elhelyezse a fban
if (!head) {
head = (struct binary_tree*)malloc(sizeof(struct
binary_tree));
head->left = NULL;
head->right = NULL;
head->number = tree_1[i];
}
//tbbi elem elhelyezse a fban
else {
Insert(head, tree_1[i]);
}
}
for (i = 0; i < sizeof(tree_2)/sizeof(int); ++i) {
//els elem elhelyezse a fban
if (!head2) {
head2 = (struct binary_tree*)malloc(sizeof(struct
binary_tree));
head2->left = NULL;
head2->right = NULL;
head2->number = tree_2[i];
}
//tbbi elem elhelyezse a fban
else {
Insert(head2, tree_2[i]);
}
}

296 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
printf("First tree:\n");
List(head);
printf("\n\nSecond tree:\n");
List(head2);
printf("\n\nThere are %d node in the first binary tree\n",
CountNode(head));
printf("There are %d leaf in the first binary tree\n",
CountLeaf(head));
printf("The max depth in the first tree is %d\n", MaxDepth(head));
printf("The max key in the first tree is: %d\n", MaxKey(head));
printf("The minimum depth in the first tree is: %d\n",
MinDepth(head));
if(SameTree(head, head2))
printf("The trees have the same shape\n");
else
printf("The trees don't have the same shape\n");
return 0;
}

void Insert(struct binary_tree* head, int temp) {
//amennyiben mr ltezik ilyen elem a fban, nem helyezzk el
mgegyszer
if (temp == (head->number))
;
else if (temp < head->number) {
if (head->left)
Insert(head->left, temp);
else {
head->left = (struct binary_tree*)malloc(sizeof(struct
binary_tree));
head->left->number = temp;
head->left->left = NULL;
head->left->right = NULL;
}
}
else if (temp > head->number) {
if (head->right)
Insert(head->right, temp);
else {
head->right = (struct binary_tree*)malloc(sizeof(struct
binary_tree));
head->right->number = temp;
head->right->left = NULL;
head->right->right = NULL;
}
}
}
void List(struct binary_tree* head) {
if (head->left)
List(head->left);
printf("%d ", head->number);
if (head->right)
List(head->right);
}
int CountNode(struct binary_tree* head) {
if (head == NULL) {
return 0;
}
else {
9. Megoldsok 297
Heckl Istvn, PE www.tankonyvtar.hu
return(CountNode(head->left) + 1 + CountNode(head->right));
}
}
int CountLeaf(struct binary_tree* head) {
if(head == NULL)
return 0;
//csak akkor tr vissza a fggvny vals rtkkel, ha az adott
cscsnak nincsenek gyerekei
if((head->left == NULL) && (head->right == NULL))
return 1;
else
return (CountLeaf(head->left) + CountLeaf(head->right));
}
int MaxDepth(struct binary_tree* head) {
int left_depth, right_depth;

if (head == NULL)
return 0;
else {
//mindegyik rszfnak meghatrozza a mlysgt
left_depth = MaxDepth(head->left);
right_depth = MaxDepth(head->right);
//annak a rszfnak hasznljuk a mlysgt, amelyik nagyobb
if (left_depth > right_depth)
return(left_depth + 1);
else
return(right_depth + 1);
}
}
//a fa rendese miatt, a legnagyobb elem nem ms, mint a jobb als elem
int MaxKey(struct binary_tree* head) {
if (head)
while(head->right)
head = head->right;
return head->number;

}
//ugyanaz mint a MaxDepth, csak azt a rszft hasznljuk, amelyik kisebb
int MinDepth(struct binary_tree* head) {
int left_depth, right_depth;

if (head == NULL)
return 0;
else {
left_depth = MaxDepth(head->left);
right_depth = MaxDepth(head->right);
if (left_depth < right_depth)
return(left_depth + 1);
else
return(right_depth + 1);
}
}
int SameTree(struct binary_tree* a, struct binary_tree* b) {
//megnzznk minden cscst, hogy ugyanannyi gyereke van-e
if (a == NULL && b == NULL)
return 1;
else if (a != NULL && b != NULL) {
return(
SameTree(a->left, b->left) &&
298 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
SameTree(a->right, b->right)
);
}
else
return 0;
}
7.1.1.
#include <stdio.h>

#define GRAPHSIZE 2048
#define INFINITY GRAPHSIZE*GRAPHSIZE
#define MAX(a, b) ((a > b) ? (a) : (b))

int e; // #non-zeros
int n; // #nodes
long dist[GRAPHSIZE][GRAPHSIZE];
long d[GRAPHSIZE]; // distances from the 0th node

void printD() {
int i;
printf("The shortest path form node 0 to node n\nnode n: ");
for (i = 1; i <= n; ++i)
printf("%10d", i);
printf("\ndistance: ");
for (i = 1; i <= n; ++i) {
printf("%10ld", d[i]);
}
printf("\n");
}

void dijkstra(int s) {
int i, k, mini;
int visited[GRAPHSIZE];

for (i = 1; i <= n; ++i) {
d[i] = INFINITY;
visited[i] = 0;
}

d[s] = 0;

for (k = 1; k <= n; ++k) {
mini = -1;
for (i = 1; i <= n; ++i)
if (!visited[i] && ((mini == -1) || (d[i] < d[mini])))
mini = i;
visited[mini] = 1;
for (i = 1; i <= n; ++i)
if (dist[mini][i])
if (d[mini] + dist[mini][i] < d[i])
d[i] = d[mini] + dist[mini][i];
}
}

int main(int argc, char *argv[]) {
int i, j;
int u, v, w;

9. Megoldsok 299
Heckl Istvn, PE www.tankonyvtar.hu
FILE *fin = fopen("dist.txt", "r");
fscanf(fin, "%d", &e);
fscanf(fin, "%d", &n);
for (i = 0; i < e; ++i)
for (j = 0; j < e; ++j)
dist[i][j] = 0;
n = -1;
for (i = 0; i < e; ++i) {
fscanf(fin, "%d%d%d", &u, &v, &w);
dist[u][v] = w;
n = MAX(u, MAX(v, n));
}
fclose(fin);
dijkstra(1);
printD();
return 0;
}

// dist.txt
6 5
1 2 3
1 3 2
2 4 6
2 5 3
3 5 7
5 4 2
7.2.1.-7.2.3.
#include <stdio.h>
#include <stdlib.h>

typedef struct Graf {
int csomopontok;
double ** matrix;
} Graf;

typedef struct El {
int pont1, pont2;
double suly;
} El;

void grafInit(Graf * graf, int meret) {
graf->csomopontok = meret;
graf->matrix = NULL;
if (meret > 0) {
int sor, oszlop;
graf->matrix = (double**) malloc(sizeof (double*) * graf-
>csomopontok);
for (sor = 0; sor < graf->csomopontok; sor++) {
graf->matrix[sor] = (double*) malloc(sizeof (double) * graf-
>csomopontok);
for (oszlop = 0; oszlop < graf->csomopontok; oszlop++) {
graf->matrix[sor][oszlop] = -1;
}
}
}
}

void grafBetolt(const char * file, Graf * graf) {
300 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
FILE * fd = fopen(file, "r");
if (fd == NULL) {
perror("Hiba");
return;
}
int sor, oszlop;
fscanf(fd, "%d", &graf->csomopontok);
graf->matrix = (double**) malloc(sizeof (double*) * graf-
>csomopontok);
for (sor = 0; sor < graf->csomopontok; sor++) {
graf->matrix[sor] = (double*) malloc(sizeof (double) * graf-
>csomopontok);
for (oszlop = 0; oszlop < graf->csomopontok; oszlop++) {
fscanf(fd, "%lg", &graf->matrix[sor][oszlop]);
}
}
fclose(fd);
}

void grafFelszabadit(Graf * graf) {
int sor;
for (sor = 0; sor < graf->csomopontok; sor++) {
free(graf->matrix[sor]);
}
free(graf->matrix);
graf->csomopontok = 0;
graf->matrix = 0;
}

double dijkstra(int start, int veg, Graf graf, int * ut) {
if (start == veg) {
return 0.0;
}
double vegtelen = 1.0 / 0.0;
int * kesz = (int*) malloc(sizeof (int) * graf.csomopontok);
int * elozo = (int*) malloc(sizeof (int) * graf.csomopontok);
double * d = (double*) malloc(sizeof (double) * graf.csomopontok);

kesz[start] = 1;
int i;
for (i = 0; i < graf.csomopontok; i++) {
kesz[i] = 0;
d[i] = vegtelen;
elozo[i] = -1;
if (graf.matrix[start][i] > -1) {
d[i] = graf.matrix[start][i]; // a start szomszedjainak
tavolsagara tudunk mar becslest adni
elozo[i] = start; // az i-be a startbol jutunk el
}
}
// mehet a kereses
for (i = 0; i < graf.csomopontok; i++) {
// keresunk egy csucsot, ami nincs bent a kesz-ben, es a tavolsag
ra minimalis
int node = 0;
// keresek olyan csomopontot ami meg nincs keszen
while (node < graf.csomopontok && kesz[node])
node++;
// ha nem talaltunk ilyent, akkor vegeztunk
9. Megoldsok 301
Heckl Istvn, PE www.tankonyvtar.hu
if (node < graf.csomopontok) {

int j;
// ha talaltunk, akkor megkerssuk a legkisebb tavolsagut
for (j = 0; j < graf.csomopontok; j++)
if (d[j] < d[node] && !kesz[j])
node = j;

kesz[node] = 1; // ezzel vegeztunk
for (j = 0; j < graf.csomopontok; j++) {
if (!kesz[j] && graf.matrix[node][j] > 0 &&
d[j] > d[node] + graf.matrix[node][j]) {
d[j] = d[node] + graf.matrix[node][j];
elozo[j] = node;
}
}
} else {
i = graf.csomopontok;
}
}

int utIndex = graf.csomopontok;
if (d[veg] < vegtelen) {

int node = veg;
while (node != start) {
ut[ --utIndex ] = node;
node = elozo[node];
}
ut[ --utIndex ] = node;
}
int ut_i;
for (ut_i = utIndex; ut_i < graf.csomopontok - 1; ut_i++)
printf("%d -- %lg -- ", ut[ut_i], graf.matrix[ut[ut_i]][ut[ut_i +
1]]);
printf("%d\n", ut[ut_i]);

double res = d[veg];
free(elozo);
free(d);
free(kesz);
return res;
}

int bejar(Graf graf, int start, int * szinek, int szin) {

int i;
int * meglatogatott = (int*) malloc(sizeof (int) * graf.csomopontok);
for (i = 0; i < graf.csomopontok; i++) {
meglatogatott[i] = 0;
}
int * nyitott = (int*) malloc(sizeof (int) * graf.csomopontok);
int nyitottCsomopontok = 0;

nyitott[0] = start;
nyitottCsomopontok++;
int node = start;
int bejart = 0;
while (nyitottCsomopontok > 0) {
302 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
node = nyitott[ --nyitottCsomopontok ];
if (meglatogatott[node] == 0) {
meglatogatott[node] = 1;
bejart++;
if (szinek != NULL) {
szinek[node] = szin;
}
}
for (i = 0; i < graf.csomopontok; i++) {
if (meglatogatott[i] == 0 && graf.matrix[node][i] > -1) {
int j = 0;
while (j < nyitottCsomopontok && nyitott[j] != i) {
j++;
}
if (j >= nyitottCsomopontok) {
nyitott[ nyitottCsomopontok++ ] = i;
}
}
}
}
free(meglatogatott);
free(nyitott);
return bejart;
}

double kruskal(Graf graf, Graf mft) {
// elek megszamlalasa
int elekSzama = 0;
int i, j;
for (i = 0; i < graf.csomopontok; i++) {
for (j = i + 1; j < graf.csomopontok; j++) {
if (graf.matrix[i][j] > -1) {
elekSzama++;
}
}
}
printf("%d el van a grafban\n", elekSzama);

// elek kigyujtese
El * elek = (El*) malloc(sizeof (El) * elekSzama);
elekSzama = 0;
for (i = 0; i < graf.csomopontok; i++) {
for (j = i + 1; j < graf.csomopontok; j++) {
if (graf.matrix[i][j] > -1) {
elek[ elekSzama ].pont1 = i;
elek[ elekSzama ].pont2 = j;
elek[ elekSzama ].suly = graf.matrix[i][j];
elekSzama++;
}
}
}
// elek rendezese
for (i = 0; i < elekSzama - 1; i++) {
int minIndex = i;
for (j = i + 1; j < elekSzama; j++) {
if (elek[ j ].suly < elek[ minIndex ].suly) {
minIndex = j;
}
}
9. Megoldsok 303
Heckl Istvn, PE www.tankonyvtar.hu
El temp = elek[ i ];
elek[ i ] = elek[ minIndex ];
elek[ minIndex ] = temp;
}

// elek beillesztese
int lefedve = 0;
int * szinek = (int*)malloc(sizeof(int) * graf.csomopontok);
for (i = 0; i < graf.csomopontok; i++) {
szinek[i] = i;
}
int elIndex = 0;
double osszSuly = 0.0;
while (elIndex < elekSzama) { //(lefedve < graf.csomopontok) {
El el = elek[ elIndex ];
if (szinek[el.pont1] != szinek[el.pont2]) {
mft.matrix[ el.pont1 ][ el.pont2 ] = el.suly;
osszSuly += el.suly;
int szinRef = szinek[el.pont1];
int szin2 = szinek[el.pont2];
for (j = 0; j < graf.csomopontok; j++) {
if (szinek[j] == szinRef) {
szinek[j] = szin2;
}
}
// egyforma szinure szinezzuk oket
}
elIndex++;
}
free(elek);
free(szinek);
return osszSuly;
}

int main() {
Graf graf;
grafInit(&graf, 0);
grafBetolt("terkep.txt", &graf);
if (graf.csomopontok == 0) {
return EXIT_FAILURE;
}
int * ut = (int*) malloc(graf.csomopontok * sizeof (int));
int start, veg;
printf("Kezdopont: ");
scanf("%d", &start);
printf("Cel: ");
scanf("%d", &veg);
double hossz = dijkstra(start, veg, graf, ut);
printf("A legrovidebb ut hossza: %lg\n", hossz);

int elerheto = bejar(graf, start, NULL, 0);
printf("A %d. pontbol %d pont erheto el\n", start, elerheto);

int * szinek = (int*) malloc(sizeof (int) * graf.csomopontok);
int i;
for (i = 0; i < graf.csomopontok; i++) {
szinek[i] = 0;
}
int pont;
304 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int komponensek = 0;
do {
pont = 0;
while (pont < graf.csomopontok && szinek[pont] > 0) {
pont++;
}
if (pont < graf.csomopontok) {
komponensek++;
elerheto = bejar(graf, pont, szinek, komponensek);
printf("A %d. komponensben %d csomopont van\n", komponensek,
elerheto);
}
} while (pont < graf.csomopontok);

grafFelszabadit(&graf);
free(ut);
free(szinek);
return EXIT_SUCCESS;
}

// terkep.txt
6
-1 16 13 -1 -1 -1
-1 -1 10 12 -1 -1
-1 4 -1 -1 14 -1
-1 -1 9 -1 -1 20
-1 -1 -1 7 -1 4
-1 -1 -1 -1 -1 -1

7.3.1.
#include <stdio.h>
#include <stdlib.h>

typedef struct Graf {
int csomopontok;
double ** matrix;
} Graf;

typedef struct El {
int pont1, pont2;
double suly;
} El;

void grafInit(Graf * graf, int meret) {
graf->csomopontok = meret;
graf->matrix = NULL;
if (meret > 0) {
int sor, oszlop;
graf->matrix = (double**) malloc(sizeof (double*) * graf-
>csomopontok);
for (sor = 0; sor < graf->csomopontok; sor++) {
graf->matrix[sor] = (double*) malloc(sizeof (double) * graf-
>csomopontok);
for (oszlop = 0; oszlop < graf->csomopontok; oszlop++) {
graf->matrix[sor][oszlop] = -1;
}
}
}
9. Megoldsok 305
Heckl Istvn, PE www.tankonyvtar.hu
}

void grafBetolt(const char * file, Graf * graf) {
FILE * fd = fopen(file, "r");
if (fd == NULL) {
perror("Hiba");
return;
}
int sor, oszlop;
fscanf(fd, "%d", &graf->csomopontok);
graf->matrix = (double**) malloc(sizeof (double*) * graf-
>csomopontok);
for (sor = 0; sor < graf->csomopontok; sor++) {
graf->matrix[sor] = (double*) malloc(sizeof (double) * graf-
>csomopontok);
for (oszlop = 0; oszlop < graf->csomopontok; oszlop++) {
fscanf(fd, "%lg", &graf->matrix[sor][oszlop]);
}
}
fclose(fd);
}

void grafFelszabadit(Graf * graf) {
int sor;
for (sor = 0; sor < graf->csomopontok; sor++) {
free(graf->matrix[sor]);
}
free(graf->matrix);
graf->csomopontok = 0;
graf->matrix = 0;
}

double kruskal(Graf graf, Graf mft) {
// elek megszamlalasa
int elekSzama = 0;
int i, j;
for (i = 0; i < graf.csomopontok; i++) {
for (j = i + 1; j < graf.csomopontok; j++) {
if (graf.matrix[i][j] > -1) {
elekSzama++;
}
}
}
printf("%d el van a grafban\n", elekSzama);

// elek kigyujtese
El * elek = (El*) malloc(sizeof (El) * elekSzama);
elekSzama = 0;
for (i = 0; i < graf.csomopontok; i++) {
for (j = i + 1; j < graf.csomopontok; j++) {
if (graf.matrix[i][j] > -1) {
elek[ elekSzama ].pont1 = i;
elek[ elekSzama ].pont2 = j;
elek[ elekSzama ].suly = graf.matrix[i][j];
elekSzama++;
}
}
}
// elek rendezese
306 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
for (i = 0; i < elekSzama - 1; i++) {
int minIndex = i;
for (j = i + 1; j < elekSzama; j++) {
if (elek[ j ].suly < elek[ minIndex ].suly) {
minIndex = j;
}
}
El temp = elek[ i ];
elek[ i ] = elek[ minIndex ];
elek[ minIndex ] = temp;
}

// elek beillesztese
int lefedve = 0;
int * szinek = (int*) malloc(sizeof (int) * graf.csomopontok);
for (i = 0; i < graf.csomopontok; i++) {
szinek[i] = i;
}
int elIndex = 0;
double osszSuly = 0.0;
while (elIndex < elekSzama) { //(lefedve < graf.csomopontok) {
El el = elek[ elIndex ];
if (szinek[el.pont1] != szinek[el.pont2]) {
mft.matrix[ el.pont1 ][ el.pont2 ] = el.suly;
mft.matrix[ el.pont2 ][ el.pont1 ] = el.suly;
osszSuly += el.suly;
int szinRef = szinek[el.pont1];
int szin2 = szinek[el.pont2];
for (j = 0; j < graf.csomopontok; j++) {
if (szinek[j] == szinRef) {
szinek[j] = szin2;
}
}
}
elIndex++;
}
free(elek);
free(szinek);
return osszSuly;
}

int main() {
Graf graf;
grafInit(&graf, 0);
grafBetolt("kruskal.txt", &graf);
if (graf.csomopontok == 0) {
return EXIT_FAILURE;
}
Graf minfeszfa;
grafInit(&minfeszfa, graf.csomopontok);

double minFeszFaHossz = kruskal(graf, minfeszfa);
printf("A minimalis feszitofa ossz sulya: %lg\n", minFeszFaHossz);
int i, j;
for (i = 0; i < minfeszfa.csomopontok; i++) {
for (j = i + 1; j < minfeszfa.csomopontok; j++) {
if (minfeszfa.matrix[i][j] > -1) {
printf("%d -- %d, suly: %lg\n", i, j,
minfeszfa.matrix[i][j]);
9. Megoldsok 307
Heckl Istvn, PE www.tankonyvtar.hu
}
}
}

grafFelszabadit(&graf);
grafFelszabadit(&minfeszfa);
return EXIT_SUCCESS;
}

// kruskal.txt
11
-1 7 -1 5 -1 -1 -1 -1 -1 -1 -1
7 -1 8 9 7 -1 -1 5 -1 -1 -1
-1 8 -1 -1 5 -1 -1 -1 -1 -1 -1
5 9 -1 -1 15 6 -1 -1 -1 -1 -1
-1 7 5 15 -1 8 9 -1 -1 -1 -1
-1 -1 -1 6 8 -1 11 7 -1 -1 -1
-1 -1 -1 -1 9 11 -1 -1 5 -1 -1
-1 5 -1 -1 7 -1 -1 -1 -1 6 -1
-1 -1 -1 -1 -1 -1 5 -1 -1 -1 10
-1 -1 -1 -1 -1 -1 -1 6 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 10 -1 -1
7.4.1.-7.4.3.
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <algorithm>
#include <limits>

using namespace std;

const double vegtelen = numeric_limits<double>::infinity();

class FlowGraph {
public:
FlowGraph();
void Betolt(string FileNev);
void Folyam(int pont1, int pont2, double f);
double Folyam(int pont1, int pont2) const;
double Maradek(int pont1, int pont2) const;
bool Szomszedok(int pont1, int pont2) const;
void ResetFolyam();
double Ki(int pont) const;
double Be(int pont) const;
int Csomopontok() const;
private:
vector< vector<double> > flow;
vector< vector<double> > matrix;
int n;

void MatrixBetolt(istream & is, vector< vector<double> > & matrix,
int n);
void Init(int mennyi);
};

FlowGraph::FlowGraph() {
n = 0;
308 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}

void FlowGraph::MatrixBetolt(istream & is, vector< vector<double> > &
matrix, int n) {
matrix.clear();
int i, j;
for (i = 0; i < this->n; i++) {
vector<double> sor;
for (j = 0; j < this->n; j++) {
double szam;
is >> szam;
if (szam == -1)
szam = vegtelen;
sor.push_back(szam);
}
matrix.push_back(sor);
}
}

void FlowGraph::Init(int mennyi) {
n = mennyi;
matrix.resize(n);
int i;
for (i = 0; i < n; i++)
matrix[i].resize(n, vegtelen);
}

void FlowGraph::Folyam(int pont1, int pont2, double f) {
flow[pont1][pont2] = f;
flow[pont2][pont1] = -f;
}

void FlowGraph::ResetFolyam() {
int i, j;
for (i = 0; i < flow.size(); i++) {
for (j = 0; j < flow.size(); j++) {
flow[i][j] = 0;
}
}
}

void FlowGraph::Betolt(string FileNev) {
ifstream ifs(FileNev.c_str());
if (ifs) {
ifs >> n;
MatrixBetolt(ifs, matrix, n);
ifs.close();
} else cout << "hibas megnyitas" << endl;
int i, j;
flow.resize(n);
for (i = 0; i < n; i++) {
flow[i].resize(n, 0);
for (j = 0; j < n; j++)
if (matrix[i][j] == vegtelen)
matrix[i][j] = -vegtelen;
}
}

double FlowGraph::Ki(int pont) const {
9. Megoldsok 309
Heckl Istvn, PE www.tankonyvtar.hu
int i;
double res = 0;
for (i = 0; i < n; i++)
if (flow[pont][i] > 0)
res += flow[pont][i];
return res;
}

double FlowGraph::Be(int pont) const {
int i;
double res = 0;
for (i = 0; i < n; i++)
if (flow[i][pont] > 0)
res += flow[i][pont];
return res;
}

bool FlowGraph::Szomszedok(int pont1, int pont2) const {
return Maradek(pont1, pont2) > 0.0;
}

double FlowGraph::Folyam(int pont1, int pont2) const {
return flow[pont1][pont2];
}

double FlowGraph::Maradek(int pont1, int pont2) const {
return matrix[pont1][pont2] - flow[pont1][pont2];
}

int FlowGraph::Csomopontok() const {
return n;
}

bool bejar(int pont1, int pont2, FlowGraph & graf, vector<int> & ut) {
int i;
set<int> visited;
vector<int> openset;
vector<int> elozo;
elozo.resize(graf.Csomopontok(), -1);
openset.push_back(pont1);
int node = pont1;
while (!openset.empty() && node != pont2) {
node = openset.back();
openset.pop_back();
visited.insert(node);
for (i = 0; i < graf.Csomopontok(); i++) {
if (visited.find(i) == visited.end() && graf.Szomszedok(node,
i)
&& find(openset.begin(), openset.end(), i) ==
openset.end()) {
openset.push_back(i);
elozo[i] = node;
}
}
}
vector<int>::iterator iter = elozo.begin();
ut.clear();
if (node == pont2) {
int node = pont2;
310 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
while (node != pont1) {
ut.insert(ut.begin(), node);
node = elozo[node];
}
ut.insert(ut.begin(), node);
}
return node == pont2;
}

double FordFulkerson(int start, int end, FlowGraph & flow) {
vector<int> ut;
do {
bejar(start, end, flow, ut);
if (ut.size() > 0) {
double min = flow.Maradek(ut[0], ut[1]);
int i;
for (i = 1; i < ut.size() - 1; i++)
if (flow.Maradek(ut[i], ut[i + 1]) < min)
min = flow.Maradek(ut[i], ut[i + 1]);

for (i = 0; i < ut.size() - 1; i++) {
flow.Folyam(ut[i], ut[i + 1], min + flow.Folyam(ut[i],
ut[i + 1]));
}
}
} while (ut.size() > 0);
return flow.Be(end);
}

void legtobbSorHova(FlowGraph & graf, int honnan) {
int maxIndex = 0;
double maxSor = 0.0;
int index;
for (index = 0; index < graf.Csomopontok(); index++) {
if (index != honnan) {
graf.ResetFolyam();
double mennyiseg = FordFulkerson(honnan, index, graf);
if (mennyiseg > maxSor) {
maxSor = mennyiseg;
maxIndex = index;
}
}
}
cout << honnan << "-bol a legtobb sor " << maxIndex << "-be
szallithato, ";
cout << "a mennyiseg: " << maxSor << endl;
}

void komponensek(FlowGraph & graf) {
vector<bool> megneztuk;
megneztuk.resize(graf.Csomopontok(), false);
int keres;
int komponensek = 0;
int maxKomponens = 0;
do {
keres = 0;
while (keres < megneztuk.size() && megneztuk[keres])
keres++;

9. Megoldsok 311
Heckl Istvn, PE www.tankonyvtar.hu
if (keres < megneztuk.size()) {
komponensek++;
int pont1 = keres;
int i;
set<int> visited;
vector<int> openset;

openset.push_back(pont1);
int node = pont1;
while (!openset.empty()) {
node = openset.back();
openset.pop_back();

visited.insert(node);
megneztuk[node] = true;

for (i = 0; i < graf.Csomopontok(); i++) {
if (visited.find(i) == visited.end() &&
graf.Szomszedok(node, i)
&& find(openset.begin(), openset.end(), i) ==
openset.end()) {
openset.push_back(i);
}
}
vector<int>::iterator iter = openset.begin();
}
if (maxKomponens < visited.size()) {
maxKomponens = visited.size();
}
}

} while (keres < megneztuk.size());
cout << "A legnagyobb komponens " << maxKomponens << " varosbol all"
<< endl;
}

int main(int argc, char** argv) {
FlowGraph graf;
graf.Betolt("pipes.txt");
int sorgyar, cel;
cout << "Hol legyen a sorgyar? " << endl;
cin >> sorgyar;
cout << "Hol legyen a cel? " << endl;
cin >> cel;

double max = FordFulkerson(sorgyar, cel, graf);
cout << sorgyar << " es " << cel << " kozott max " << max << "
mennyisegu sor szallithato" << endl;

legtobbSorHova(graf, sorgyar);
graf.ResetFolyam();
komponensek(graf);
return 0;
}


// pipes.txt
6
-1 16 13 -1 -1 -1
312 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
-1 -1 10 12 -1 -1
-1 4 -1 -1 14 -1
-1 -1 9 -1 -1 20
-1 -1 -1 7 -1 4
-1 -1 -1 -1 -1 -1
7.5.1.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define SIZE 7

struct connected_nodes {
int connected_node;
struct connected_nodes* next;
};
struct nodes {
int node;
int clas;
int visited;
struct connected_nodes* edges;
struct nodes* next;
};
struct list {
struct nodes* actual;
struct list* next;
};
void CreateGraph(int, int**, struct nodes*);
int BFS(struct nodes*);
void CreateList(struct nodes*, struct list**, struct list**);
void FreeList(struct list**);

int main() {
int i, j;
struct nodes my_node;
int** dynamic_matrix = NULL;
int adjacenci_matrix[SIZE][SIZE] = {
{0, 0, 0, 1, 1, 1, 0},
{0, 0, 0, 1, 1, 0, 0},
{0, 0, 0, 0, 1, 0, 1},
{1, 1, 0, 0, 0, 0, 0},
{1, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0}
};

//ltrehozunk egy dinamikus tmbt, hogy t tudjuk adni azt egy
fggvnynek paramterknt
dynamic_matrix = (int**)malloc(SIZE*sizeof(int*));
for (i = 0; i < SIZE; ++i) {
dynamic_matrix[i] = (int*)malloc(SIZE*sizeof(int));
}
for(i = 0; i < SIZE; ++i)
for (j = 0; j < SIZE; ++j)
dynamic_matrix[i][j] = adjacenci_matrix[i][j];

my_node.edges = NULL;
my_node.next = NULL;
9. Megoldsok 313
Heckl Istvn, PE www.tankonyvtar.hu
my_node.node = 0;
CreateGraph(SIZE, dynamic_matrix, &my_node);
if (BFS(&my_node)) {
printf("\nThe graph is not bipartite!\n");
}
else {
printf("\nThe nodes have been divided into two disjoint sets.\n");
printf("The graph is bipartite.\n");
}
for (i = 0; i < SIZE; ++i) {
free(dynamic_matrix[i]);
}
free(dynamic_matrix);
return 0;
}

void CreateGraph(int size, int** adjacenci_matrix, struct nodes* my_node)
{
int i = 0, j = 0;
struct connected_nodes* temp_ptr;
my_node->node = 0;
my_node->visited = 0;
my_node->clas = 0;
//az els cscs szomszdaink meghatrozsa
for(i = 0; i < size; ++i) {
if(adjacenci_matrix[0][i]) {
//tbbi szomszd
if (my_node->edges) {
temp_ptr->next = (struct connected_nodes*)malloc(sizeof
(struct connected_nodes));
temp_ptr = temp_ptr->next;
temp_ptr->connected_node = i;
temp_ptr->next = NULL;
}
//els szomszd
else {
my_node->edges = (struct connected_nodes*)malloc(sizeof
(struct connected_nodes));
temp_ptr = my_node->edges;
temp_ptr->connected_node = i;
temp_ptr->next = NULL;
}
}
}
//tbbi cscs szomszdainak keresse
for(i = 1; i < size; ++i) {
my_node->next = (struct nodes*)malloc(sizeof (struct nodes));
my_node = my_node->next;
my_node->node = i;
my_node->next = NULL;
my_node->edges = NULL;
my_node->visited = 0;
my_node->clas = 0;
for(j = 0; j < size; ++j) {
if(adjacenci_matrix[i][j]) {
if (my_node->edges) {
temp_ptr->next = (struct connected_nodes*)malloc(sizeof
(struct connected_nodes));
temp_ptr = temp_ptr->next;
314 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
temp_ptr->connected_node = j;
temp_ptr->next = NULL;
}
else {
my_node->edges = (struct connected_nodes*)malloc(sizeof
(struct connected_nodes));
temp_ptr = my_node->edges;
temp_ptr->connected_node = j;
temp_ptr->next = NULL;
}
}
}
}
}
int BFS(struct nodes* root) {
int current_node;
struct connected_nodes* cn_temp;
struct nodes* n_temp;
struct list* list_temp, *list_temp1, * list_temp2,
*list_temp_for_print;

//kt listt fogok kszteni, mindig az els listbl generljuk a
kvetkezt,
//az els lista tartalmazza az adott szint cscsait, a msodik listt
gy ebbl fogjuk generlni,
//amint ksz van, tlltjuk a mutatjt, hogy ez legyen az els
lista
list_temp2 = NULL;
root->clas = 1;
root->visited = 1;
//elksztem az els listt, 1 elemmel
printf("Creating first list (nodes in the current list): ");
list_temp1 = (struct list*)malloc(sizeof(struct list));
list_temp1->actual = root;
list_temp1->next = NULL;
list_temp_for_print = list_temp1;
while (list_temp_for_print) {
printf("%d ", list_temp_for_print->actual->node);
list_temp_for_print = list_temp_for_print->next;
}
printf("\n");

while (list_temp1) {
list_temp = list_temp1;
while (list_temp) {
cn_temp = list_temp->actual->edges;
//van-e szomszdja az adott cscsnak
while (cn_temp) {
//melyik az?
current_node = cn_temp->connected_node;
n_temp = root;
//rltjuk az n_temp pointert
while (n_temp->node != current_node)
n_temp = n_temp->next;
//megnzzk, hogy bejrtuk-e mr, ha nem, akkor de s
belltjuk az ellenttes osztlyt
if (n_temp->visited == 0) {
//a 2 jelzi, hgoy az adott cscsot meg fogjuk
ltogatni, nehogy felfzznk a kvetkez listba azt is ami mr volt
9. Megoldsok 315
Heckl Istvn, PE www.tankonyvtar.hu
n_temp->visited = 2;
n_temp->clas = (-1) * list_temp1->actual->clas;
}
//ha mr bejrtuk, akkor megvizsgljuk, hogy egyeznek-e az
osztlyaik
else {
if (list_temp1->actual->clas == n_temp->clas)
return 1;
else {
;
}
}
//nzzk a kvetkez szomszdot
cn_temp = cn_temp->next;
}
list_temp = list_temp->next;
}
//ksztjk a kvetkez listt
//ha elsszr ksztnk listt
printf("Creating next list (nodes in the current list): ");
CreateList(root, &list_temp1, &list_temp2);
FreeList(&list_temp1);
list_temp1 = list_temp2;
list_temp2 = NULL;
list_temp_for_print = list_temp1;
while (list_temp_for_print) {
printf("%d ", list_temp_for_print->actual->node);
list_temp_for_print = list_temp_for_print->next;
}
printf("\n");
}
return 0;
}
void CreateList(struct nodes* root, struct list** ptr1, struct list**
ptr2) {
struct nodes* n_temp;
struct connected_nodes* connected_node_temp;
struct list *first_list_temp, *second_list_temp;
int current_node;

first_list_temp = *ptr1;
//ameddig ltezik az els listnak eleme, lpegetnk rajta
while(first_list_temp) {
connected_node_temp = first_list_temp->actual->edges;
//ameddig egy elemnek ltezik szomszdja, azokat fzzk fel a
msodik listba
while (connected_node_temp) {
//megkeressk, hogy ez a szomszd melyik cscs is valjban
current_node = connected_node_temp->connected_node;
n_temp = root;
while (n_temp->node != current_node)
n_temp = n_temp->next;
//els elem elhelyezse, de csak azt amit mg egyltaln nem
jrtunk be, erre kell a 2-es jelz
if (!(*ptr2) && (n_temp->visited == 2)) {
n_temp->visited = 1;
(*ptr2) = (struct list*)malloc(sizeof(struct list));
(*ptr2)->actual = n_temp;
(*ptr2)->next = NULL;
316 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
second_list_temp = *ptr2;
}
//tbbi elem elhelyezse, de csak azt amit mg egyltaln nem
jrtunk be
else if(n_temp->visited == 2) {
n_temp->visited = 1;
second_list_temp->next = (struct
list*)malloc(sizeof(struct list));
second_list_temp = second_list_temp->next;
second_list_temp->actual = n_temp;
second_list_temp->next = NULL;
}
connected_node_temp = connected_node_temp->next;
}
first_list_temp = first_list_temp->next;
}
}
void FreeList(struct list** head) {
struct list* temp1, *temp2;

temp1 = (*head);
while (temp1) {
temp2 = temp1->next;
free(temp1);
temp1 = temp2;
}
*head = NULL;
}
7.6.1.
#include <stdio.h>

typedef struct {
int u, v, weight;
}Edge;

#define INFINITY 10000
#define SIZE 5

void BellmanFord(int, int, int, int*, Edge*);
void PrintDistances(int, int[]);

int main() {
Edge edges[1024];
int i, j;
int edges_num = 0, source_node = 2;
int distances_from_source[SIZE];
int adjacenci_matrix[SIZE][SIZE] = {
{0, 6, 0, 7, 0},
{0, 0, 5, 8, -4},
{0, -2, 0, 0, 0},
{0, 0, -3, 9, 0},
{2, 0, 7, 0, 0}
};
printf("The adjacenci matrix:\n");

for (i = 0; i < SIZE; ++i) {
for (j = 0; j < SIZE; ++j) {
printf("%d ", adjacenci_matrix[i][j]);
9. Megoldsok 317
Heckl Istvn, PE www.tankonyvtar.hu
if (adjacenci_matrix[i][j] != 0) {
edges[edges_num].u = i;
edges[edges_num].v = j;
edges[edges_num].weight = adjacenci_matrix[i][j];
edges_num++;
}
}
printf("\n");
}
printf("\nRun Belmann-Ford algorithm to node %d\n", source_node);
BellmanFord(source_node, SIZE, edges_num, distances_from_source,
edges);
printf("\nMinimal distances from node %d:\n", source_node);
PrintDistances(SIZE, distances_from_source);
return 0;
}

void PrintDistances(int size, int* distances_from_source) {
int i;

for (i = 0; i < size; ++i)
printf("to %d\t", i + 1);
printf("\n");

for (i = 0; i < size; ++i)
printf("%d\t", distances_from_source[i]);

printf("\n");
}

void BellmanFord(int source, int size, int edges_num, int*
distances_from_source, Edge* edges) {
int i, j;

for (i = 0; i < size; ++i)
distances_from_source[i] = INFINITY;

distances_from_source[source] = 0;

for (i = 0; i < size - 1; ++i)
for (j = 0; j < edges_num; ++j)
if (distances_from_source[edges[j].u] + edges[j].weight <
distances_from_source[edges[j].v])
distances_from_source[edges[j].v] =
distances_from_source[edges[j].u] + edges[j].weight;
}
7.6.2.
#include <stdio.h>

typedef struct {
int u, v, weight;
}Edge;

#define INFINITY 10000
#define SIZE 8

int BellmanFord(int, int, int, int*, Edge*);
void PrintDistances(int, int[]);
318 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE

int main() {
Edge edges[1024];
int i, j, max_distance = 0, temp_max_distance;
int edges_num = 0;
int distances_from_source[SIZE];
int adjacenci_matrix[SIZE][SIZE] = {
{0, 1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 0, 0, 0, 0},
{1, 0, 0, 0, 1, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 1},
{0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0},
};
printf("Adjacenci matrix:\n");
for (i = 0; i < SIZE; ++i) {
for (j = 0; j < SIZE; ++j) {
printf("%d ", adjacenci_matrix[i][j]);
if (adjacenci_matrix[i][j] != 0) {
edges[edges_num].u = i;
edges[edges_num].v = j;
edges[edges_num].weight = adjacenci_matrix[i][j];
edges_num++;
}
}
printf("\n");
}
for (i = 0;i < SIZE; ++i) {
temp_max_distance = BellmanFord(i, SIZE, edges_num,
distances_from_source, edges);
PrintDistances(SIZE, distances_from_source);
if (temp_max_distance > max_distance)
max_distance = temp_max_distance;
}
printf("\nThe tree's diameter is: %d\n", max_distance);
return 0;
}

void PrintDistances(int size, int* distances_from_source) {
int i;

printf("Distances from ");
for (i = 0; i < size; ++i) {
if (distances_from_source[i] == 0)
printf("%d:\n", i+1);
}
for (i = 0; i < size; ++i)
printf("to %d\t", i + 1);
printf("\n");
for (i = 0; i < size; ++i)
printf("%d\t", distances_from_source[i]);
printf("\n");
}

int BellmanFord(int source, int size, int edges_num, int*
distances_from_source, Edge* edges) {
int i, j, max = 0;
9. Megoldsok 319
Heckl Istvn, PE www.tankonyvtar.hu

for (i = 0; i < size; ++i)
distances_from_source[i] = INFINITY;
distances_from_source[source] = 0;
for (i = 0; i < size - 1; ++i) {
for (j = 0; j < edges_num; ++j) {
if (distances_from_source[edges[j].u] + edges[j].weight <
distances_from_source[edges[j].v]) {
distances_from_source[edges[j].v] =
distances_from_source[edges[j].u] + edges[j].weight;
}
}
}
for (i = 0; i < size; ++i) {
if (distances_from_source[i] > max)
max = distances_from_source[i];
}
return max;
}
7.6.3.
#include <stdio.h>

typedef struct {
int u, v;
float weight;
}Edge;

#define INFINITY 10000
#define SIZE 3

void ModifiedBellmanFord(int, int, int, float*, Edge*);
void PrintMaxMoney(int, float[]);

int main() {
Edge edges[1024];
int i, j;
int edges_num = 0, source_node = 0;
float distances_from_source[SIZE];
float adjacenci_matrix[SIZE][SIZE] = {
{1, 2, 3},
{1./2, 1, 1./4},
{1./3, 4, 1}
};
printf("Adjacenci matrix for exchange table:\n");
for (i = 0; i < SIZE; ++i) {
for (j = 0; j < SIZE; ++j) {
printf("%f ", adjacenci_matrix[i][j]);
if (adjacenci_matrix[i][j] != 0) {
edges[edges_num].u = i;
edges[edges_num].v = j;
edges[edges_num].weight = adjacenci_matrix[i][j];
edges_num++;
}
}
printf("\n");
}
ModifiedBellmanFord(source_node, SIZE, edges_num,
distances_from_source, edges);
320 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
PrintMaxMoney(SIZE, distances_from_source);
return 0;
}

void PrintMaxMoney(int size, float* distances_from_source) {
int i;

printf("\nMax money at current currancys:\n");

for (i = 0; i < size; ++i)
printf("at %d\t\t", i + 1);
printf("\n");
for (i = 0; i < size; ++i)
printf("%f\t", distances_from_source[i]);
printf("\n");
}
void ModifiedBellmanFord(int source, int size, int edges_num, float*
distances_from_source, Edge* edges) {
int i, j;


for (i = 0; i < size; ++i)
distances_from_source[i] = 0;
distances_from_source[source] = 1;
for (i = 0; i < size - 1; ++i) {
for (j = 0; j < edges_num; ++j) {
if (distances_from_source[edges[j].u] * edges[j].weight >
distances_from_source[edges[j].v]) {
distances_from_source[edges[j].v] =
distances_from_source[edges[j].u] * edges[j].weight;
}
}
}
}
7.7.1.
#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

struct edges {
int current_node;
struct edges* next;
};
struct node {
int parent;
int current_node;
struct edges* current_node_edges;
struct node* next;
};
struct edge_list {
int u;
int v;
int weight;
struct edge_list* next;
};

void Union(int, int, int, struct node*, struct node*);
9. Megoldsok 321
Heckl Istvn, PE www.tankonyvtar.hu
int Where(int, int, int, struct node*, struct node*);
void CreateDisjunctGraphs(struct node*, int);
void FreeGraph(struct node*);
void FreeGraphList(struct node*);
void SortByWeight(struct edge_list**);
void FreeEdgeList(struct edge_list*);

int main() {
int temp_num, i, j, k;
//segdvltozk, egy l kt vgpontjhoz
int source, destiny;
//segdvltozk a HOLVAN mvelet elvgzshez, ezekben trolom, hogy
egy l kt vgpontja melyik grfban van
int destiny_disjunct_graph_root, source_disjunct_graph_root;
//az a grf amiben trolom a mg diszjunk grfokat
struct node my_disjunct_graph;
//segdlista az HOLVAN mvelet elvgzshez
struct node nodes_in_row, *nodes_in_row_temp;
//a hlozat leinek trolsra szolgl lista a rendezs eltt
struct edge_list* my_edge_list = NULL;
//segdlista a hlozat leinek a rendezshez
struct edge_list *edge_list_temp;
//segdvltoz tmentei llapot kiratshoz
struct edges* edges_temp;
//mindig a rendezett lista elejre mutat
struct edge_list* my_sorted_edge_list;
int adjacenci_matrix[SIZE][SIZE] = {
{0, 3, 1, 0, 9},
{0, 4, 2, 4, 0},
{0, 4, 0, 1, 7},
{2, 0, 5, 0, 0},
{1, 0, 3, 0, 4}
};

//hlozat beolvassa
printf("The adjacenci matrix:\n");
for (i = 0; i < SIZE; ++i) {
for (k = 0; k < i; ++k)
printf("0 ");
for (j = i; j < SIZE; ++j) {
printf("%d ", adjacenci_matrix[i][j]);
if (adjacenci_matrix[i][j] != 0) {
//els elem beszrsa egy listba, amit ksbb cskken
sorrendbe rendeznk
if (!my_edge_list) {
my_edge_list = (struct edge_list*)malloc(sizeof(struct
edge_list));
edge_list_temp = my_edge_list;
edge_list_temp->next = NULL;
edge_list_temp->u = i+1;
edge_list_temp->v = j+1;
edge_list_temp->weight = adjacenci_matrix[i][j];
}
//tbi elem beszrsa a listba
else {
edge_list_temp->next = (struct
edge_list*)malloc(sizeof(struct edge_list));
edge_list_temp = edge_list_temp->next;
edge_list_temp->next = NULL;
322 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
edge_list_temp->u = i+1;
edge_list_temp->v = j+1;
edge_list_temp->weight = adjacenci_matrix[i][j];
}
}
}
printf("\n");
}
//az elbb elksztett lista rendezse
SortByWeight(&my_edge_list);
my_sorted_edge_list = my_edge_list;
edge_list_temp = my_sorted_edge_list;
my_edge_list = my_edge_list->next;
while (my_edge_list) {
//a segdlista elejre tesszk a legnagyobb elemet
SortByWeight(&my_edge_list);
//a rendezett lista kvetkez eleme gy mindig a kvetkez
legnagyobb rtk lesz, ami mg megmaradt a segdlistban
edge_list_temp->next = my_edge_list;
edge_list_temp = edge_list_temp->next;
//a segdlista els elemt kiszedem a segdlistbl, a kvetkez
legnagyobb elemet szeretnm megtallni a htralev elemek kztt
my_edge_list = my_edge_list->next;
}
edge_list_temp = my_sorted_edge_list;
printf("\nList of the links from the biggest:\n");
while (edge_list_temp) {
printf("Link (%d-%d), weight: %d\n", edge_list_temp->u,
edge_list_temp->v, edge_list_temp->weight );
edge_list_temp = edge_list_temp->next;
}
//elksztem a diszjunkt grfokat, eleinte minden pont kpez egy
kln grfot
CreateDisjunctGraphs(&my_disjunct_graph, SIZE);
//ltrehozom a segdlistt is az HOLVAN mvelethez
CreateDisjunctGraphs(&nodes_in_row, SIZE);

//segdvltozval vgigmegyek a rendezett llistmon
edge_list_temp = my_sorted_edge_list;
while (edge_list_temp) {
printf("\nDisjunct graphs, before analyse link (%d-%d) with weight
%d:\n", edge_list_temp->u, edge_list_temp->v, edge_list_temp->weight);
nodes_in_row_temp = &my_disjunct_graph;
while (nodes_in_row_temp) {
printf("Root nood: %d the link(s): ", nodes_in_row_temp-
>current_node);
edges_temp = nodes_in_row_temp->current_node_edges;
while(edges_temp) {
printf("%d ", edges_temp->current_node);
edges_temp = edges_temp->next;
}
printf("\n");
nodes_in_row_temp = nodes_in_row_temp->next;
}
//az ppen aktulis l kt vgpontjt eltrolom
destiny = edge_list_temp->u;
source = edge_list_temp->v;
//megnzem, hogy melyik grfokban vannak ezek az lek
9. Megoldsok 323
Heckl Istvn, PE www.tankonyvtar.hu
destiny_disjunct_graph_root = Where(0, 0, destiny,
&my_disjunct_graph, &nodes_in_row);
source_disjunct_graph_root = Where(0, 0, source,
&my_disjunct_graph, &nodes_in_row);

//a fgvny csak akkor mkdik, ha a cl grf gykere kissebb,
mint a msik grf
if (destiny_disjunct_graph_root > source_disjunct_graph_root) {
temp_num = destiny_disjunct_graph_root;
destiny_disjunct_graph_root = source_disjunct_graph_root;
source_disjunct_graph_root = temp_num;
}
//ha az l kt vge nem ugyanabban a grfban van, elvgezzk az
UNI mveletet
if (destiny_disjunct_graph_root != source_disjunct_graph_root) {
Union(SIZE, destiny_disjunct_graph_root,
source_disjunct_graph_root, &my_disjunct_graph, &nodes_in_row);
}
else {
printf("The nodes are in the same graph!\n");
}
//ha elkszlt a fesztfnk, kirjuk a hlozat maximlis
svszlessgt
if (!my_disjunct_graph.next) {
printf("\nPerfect, only one graph remain.\n");
printf("The minimum spanning tree has been created, the last
link weight is: %d\n", edge_list_temp->weight);
break;
}
edge_list_temp = edge_list_temp->next;
}
//ha mg maradt legalbb kt egymstl diszjunk grf, akkor a
svszlessg 0 lesz
if (my_disjunct_graph.next) {
printf("\nSorry, more than one graph remain.\n");
printf("Cannot create minimum spanning tree!\n");
}

FreeGraph(&my_disjunct_graph);
FreeGraphList(&nodes_in_row);
FreeEdgeList(my_sorted_edge_list);
return 0;
}

void CreateDisjunctGraphs(struct node* my_node, int size) {
int i;

my_node->parent = 1;
my_node->current_node = 1;
my_node->current_node_edges = NULL;
my_node->next = NULL;
for(i = 2; i <= size; ++i) {
my_node->next = (struct node*)malloc(sizeof(struct node));
my_node = my_node->next;
my_node->parent = i;
my_node->current_node = i;
my_node->current_node_edges = NULL;
my_node->next = NULL;
}
324 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
int Where(int recursion, int temp_parent, int u, struct node* actual,
struct node* original) {
int i = 0;
struct node* temp;
struct edges* temp_edge;

//az actual a diszjunk grfokbl kpezett listn megy vgig (a
gykerein)
while (actual) {
//ha megtalltuk a keresett cscsot, visszatrsi rtknek
megadjuk, melyik grfba tartozik
if (u == actual->current_node || temp_parent)
return actual->parent;
else {
//ha az adott cscsnak ltezik gyereke, akkor meghvjuk r a
HOLVAN fggvnyt
temp_edge = actual->current_node_edges;
while (temp_edge) {
temp = original;
//megkeressk a segdlistn az adott gyereket
while(temp_edge->current_node != temp->current_node)
temp = temp->next;
temp_parent = Where(1, temp_parent, u, temp, original);
//ha mr megtalltuk a cscsot a grfban, ne nzzk tovbb
a tbbi gyereket is, trjnk vissza a megfelel rtkkel, a rekurzi
miatt
if (temp_parent)
return actual->parent;
temp_edge = temp_edge->next;
}
}
if (recursion)
return 0;
actual = actual->next;
}
return 0;
}
void Union(int size, int destiny, int source, struct node*
my_dijunct_graphs , struct node* original) {
struct node* temp_node, *source_node, *source_node_prev,
*destiny_node;
struct edges* temp_edge;

source_node = my_dijunct_graphs;
destiny_node = my_dijunct_graphs;
//megkeressk, hol van a kt grf gykere, amikre el szeretnnk
vgezni az UNNI mveletet
while (source_node->current_node != source) {
source_node_prev = source_node;
source_node = source_node->next;
}
while (destiny_node->current_node != destiny)
destiny_node = destiny_node->next;

//ha a source s a destiny grfok egyms utn vannak a diszjunk
grfokat tartalmaz listban
//kivesszk a diszjunk grfok listjbl a source elemet
if (destiny_node->next->current_node == source) {
9. Megoldsok 325
Heckl Istvn, PE www.tankonyvtar.hu
destiny_node->next = source_node->next;
source_node->next = NULL;
//tlltom a szljt, gy a HOLVAN mvelet visszatrsi rtke
konzisztens lesz
source_node->parent = destiny_node->parent;
//megkeressk a source elemet az eredeti listban is
temp_node = original;
while(temp_node->current_node != source)
temp_node = temp_node->next;
//tlltjuk neki is a szljt
temp_node->parent = destiny_node->parent;

//megnzzk, az adott cscsnak vannak-e szomszdai
//ha mg nincs, megcsiinljuk az elst
if (!destiny_node->current_node_edges) {
destiny_node->current_node_edges = (struct
edges*)malloc(sizeof(struct edges));
destiny_node->current_node_edges->next = NULL;
destiny_node->current_node_edges->current_node = source_node-
>current_node;
//az eredeti listnl is belltjuk a destiny cscs
szomszdait
temp_node = original;
while (temp_node->current_node != destiny_node->current_node)
temp_node = temp_node->next;
temp_node->current_node_edges = destiny_node-
>current_node_edges;
}
//ha van mr szomszd, akkor megkeressk a lncolt lista vgt s
oda szrjuk be az j elemet
else {
temp_edge = destiny_node->current_node_edges;
while (temp_edge->next)
temp_edge = temp_edge->next;
temp_edge->next = (struct edges*)malloc(sizeof(struct edges));
temp_edge = temp_edge->next;
temp_edge->current_node = source;
temp_edge->next = NULL;
}
}
//ha nem egyms utn vannak a listban a sorce s a destiny grfok
else {
source_node_prev->next = source_node->next;
source_node->next = NULL;
source_node->parent = destiny_node->parent;
temp_node = original;
while(temp_node->current_node != source)
temp_node = temp_node->next;
temp_node->parent = destiny_node->parent;
temp_edge = destiny_node->current_node_edges;
if (!destiny_node->current_node_edges) {
destiny_node->current_node_edges = (struct
edges*)malloc(sizeof(struct edges));
destiny_node->current_node_edges->next = NULL;
destiny_node->current_node_edges->current_node = source_node-
>current_node;
temp_node = original;
while (temp_node->current_node != destiny_node->current_node)
temp_node = temp_node->next;
326 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
temp_node->current_node_edges = destiny_node-
>current_node_edges;
}
else {
temp_edge = destiny_node->current_node_edges;
while (temp_edge->next)
temp_edge = temp_edge->next;
temp_edge->next = (struct edges*)malloc(sizeof(struct edges));
temp_edge = temp_edge->next;
temp_edge->current_node = source;
temp_edge->next = NULL;
}
}
}
void SortByWeight(struct edge_list** root) {
int min;
struct edge_list* temp, *temp_prev, *min_weight, *min_weight_prev;

//elsszr belltjuk, hogy a lista els eleme legyen a legnagyobb
temp_prev = *root;
temp = temp_prev->next;
min_weight = *root;
min_weight_prev = NULL;
min = (*root)->weight;
//vgigmegynk a listn s megkeressnk a tnyleges legnagyobb elemet
while (temp) {
if (temp->weight < min) {
min = temp->weight;
min_weight = temp;
min_weight_prev = temp_prev;
temp_prev = temp;
temp = temp->next;
}
else {
temp_prev = temp;
temp = temp->next;
}
}
//mutatk tlltsa, hogy a legnagyobb elem legyen ell
//ha a lista els eleme a legnagyobb elem, akkor nem kell semmit se
csinlni
if (!min_weight_prev)
;
//ha a msodik a legnagyobb elem
else if (min_weight_prev == (*root)) {
(*root)->next = min_weight->next;
min_weight->next = min_weight_prev;
(*root) = min_weight;
}
//egybknt
else {
min_weight_prev->next = min_weight->next;
min_weight->next = (*root);
(*root) = min_weight;
}
}
void FreeGraph(struct node* root) {
struct edges* temp_edge1, *temp_edge2;
struct node* temp_node1, *temp_node2;
9. Megoldsok 327
Heckl Istvn, PE www.tankonyvtar.hu

temp_edge1 = root->current_node_edges;
while (temp_edge1) {
temp_edge2 = temp_edge1;
temp_edge1 = temp_edge1->next;
free(temp_edge2);
}

temp_node1 = root->next;
while (temp_node1) {
temp_edge1 = temp_node1->current_node_edges;
while (temp_edge1) {
temp_edge2 = temp_edge1;
temp_edge1 = temp_edge1->next;
free(temp_edge2);
}
temp_node2 = temp_node1;
temp_node1 = temp_node1->next;
free(temp_node2);
}
}
void FreeGraphList(struct node* root) {
struct node* temp_node1, *temp_node2;

temp_node1 = root->next;
while (temp_node1) {
temp_node2 = temp_node1;
temp_node1 = temp_node1->next;
free(temp_node2);
}
}
void FreeEdgeList(struct edge_list* temp1) {
struct edge_list* temp2;

while(temp1) {
temp2 = temp1;
temp1 = temp1->next;
free(temp2);
}
}
7.7.2.
#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

struct edges {
int current_node;
struct edges* next;
};
struct node {
int parent;
int current_node;
struct edges* current_node_edges;
struct node* next;
};
struct edge_list {
int u;
328 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int v;
int weight;
struct edge_list* next;
};

void Union(int, int, int, struct node*, struct node*);
int Where(int, int, int, struct node*, struct node*);
void CreateDisjunctGraphs(struct node*, int);
void FreeGraph(struct node*);
void FreeGraphList(struct node*);
void SortByWeight(struct edge_list**);
void FreeEdgeList(struct edge_list*);

int main() {
int temp_num, i, j;
//segdvltozk, egy l kt vgpontjhoz
int source, destiny;
//segdvltozk a HOLVAN mvelet elvgzshez, ezekben trolom, hogy
egy l kt vgpontja melyik grfban van
int destiny_disjunct_graph_root, source_disjunct_graph_root;
//az a grf amiben trolom a mg diszjunk grfokat
struct node my_disjunct_graph;
//segdlista az HOLVAN mvelet elvgzshez
struct node nodes_in_row, *nodes_in_row_temp;
//a hlozat leinek trolsra szolgl lista a rendezs eltt
struct edge_list* my_edge_list = NULL;
//segdlista a hlozat leinek a rendezshez
struct edge_list *edge_list_temp;
//segdvltoz tmentei llapot kiratshoz
struct edges* edges_temp;
//mindig a rendezett lista elejre mutat
struct edge_list* my_sorted_edge_list;
int adjacenci_matrix[SIZE][SIZE] = {
{0, 0, 5, 0, 3},
{0, 6, 9, 0, 8},
{0, 8, 0, 2, 0},
{6, 2, 5, 0, 5},
{5, 0, 5, 1, 0}
};

//hlozat beolvassa
printf("The adjacenci matrix:\n");
for (i = 0; i < SIZE; ++i) {
for (j = 0; j < SIZE; ++j) {
printf("%d ", adjacenci_matrix[i][j]);
if (adjacenci_matrix[i][j] != 0) {
//els elem beszrsa egy listba, amit ksbb cskken
sorrendbe rendeznk
if (!my_edge_list) {
my_edge_list = (struct edge_list*)malloc(sizeof(struct
edge_list));
edge_list_temp = my_edge_list;
edge_list_temp->next = NULL;
edge_list_temp->u = i+1;
edge_list_temp->v = j+1;
edge_list_temp->weight = adjacenci_matrix[i][j];
}
//tbi elem beszrsa a listba
else {
9. Megoldsok 329
Heckl Istvn, PE www.tankonyvtar.hu
edge_list_temp->next = (struct
edge_list*)malloc(sizeof(struct edge_list));
edge_list_temp = edge_list_temp->next;
edge_list_temp->next = NULL;
edge_list_temp->u = i+1;
edge_list_temp->v = j+1;
edge_list_temp->weight = adjacenci_matrix[i][j];
}
}
}
printf("\n");
}
//az elbb elksztett lista rendezse
SortByWeight(&my_edge_list);
my_sorted_edge_list = my_edge_list;
edge_list_temp = my_sorted_edge_list;
my_edge_list = my_edge_list->next;
while (my_edge_list) {
//a segdlista elejre tesszk a legnagyobb elemet
SortByWeight(&my_edge_list);
//a rendezett lista kvetkez eleme gy mindig a kvetkez
legnagyobb rtk lesz, ami mg megmaradt a segdlistban
edge_list_temp->next = my_edge_list;
edge_list_temp = edge_list_temp->next;
//a segdlista els elemt kiszedem a segdlistbl, a kvetkez
legnagyobb elemet szeretnm megtallni a htralev elemek kztt
my_edge_list = my_edge_list->next;
}
edge_list_temp = my_sorted_edge_list;
printf("\nList of the links from the biggest:\n");
while (edge_list_temp) {
printf("Link (%d-%d), weight: %d\n", edge_list_temp->u,
edge_list_temp->v, edge_list_temp->weight );
edge_list_temp = edge_list_temp->next;
}
//elksztem a diszjunkt grfokat, eleinte minden pont kpez egy
kln grfot
CreateDisjunctGraphs(&my_disjunct_graph, SIZE);
//ltrehozom a segdlistt is az HOLVAN mvelethez
CreateDisjunctGraphs(&nodes_in_row, SIZE);

//segdvltozval vgigmegyek a rendezett llistmon
edge_list_temp = my_sorted_edge_list;
while (edge_list_temp) {
printf("\nDisjunct graphs, before analyse link (%d-%d) with weight
%d:\n", edge_list_temp->u, edge_list_temp->v, edge_list_temp->weight);
nodes_in_row_temp = &my_disjunct_graph;
while (nodes_in_row_temp) {
printf("Root nood: %d the link(s): ", nodes_in_row_temp-
>current_node);
edges_temp = nodes_in_row_temp->current_node_edges;
while(edges_temp) {
printf("%d ", edges_temp->current_node);
edges_temp = edges_temp->next;
}
printf("\n");
nodes_in_row_temp = nodes_in_row_temp->next;
}
//az ppen aktulis l kt vgpontjt eltrolom
330 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
destiny = edge_list_temp->u;
source = edge_list_temp->v;
//megnzem, hogy melyik grfokban vannak ezek az lek
destiny_disjunct_graph_root = Where(0, 0, destiny,
&my_disjunct_graph, &nodes_in_row);
source_disjunct_graph_root = Where(0, 0, source,
&my_disjunct_graph, &nodes_in_row);

//a fgvny csak akkor mkdik, ha a cl grf gykere kissebb,
mint a msik grf
if (destiny_disjunct_graph_root > source_disjunct_graph_root) {
temp_num = destiny_disjunct_graph_root;
destiny_disjunct_graph_root = source_disjunct_graph_root;
source_disjunct_graph_root = temp_num;
}
//ha az l kt vge nem ugyanabban a grfban van, elvgezzk az
UNI mveletet
if (destiny_disjunct_graph_root != source_disjunct_graph_root) {
Union(SIZE, destiny_disjunct_graph_root,
source_disjunct_graph_root, &my_disjunct_graph, &nodes_in_row);
}
else {
printf("The nodes are in the same graph!\n");
}
//ha elkszlt a fesztfnk, kirjuk a hlozat maximlis
svszlessgt
if (!my_disjunct_graph.next) {
printf("\nPerfect, only one graph remain.\n");
printf("The network's bandwidth: %d\n", edge_list_temp-
>weight);
break;
}
edge_list_temp = edge_list_temp->next;
}
//ha mg maradt legalbb kt egymstl diszjunk grf, akkor a
svszlessg 0 lesz
if (my_disjunct_graph.next) {
printf("\nSorry, more than one graph remains.\n");
printf("The network's bandwidth: 0\n");
}

FreeGraph(&my_disjunct_graph);
FreeGraphList(&nodes_in_row);
FreeEdgeList(my_sorted_edge_list);
return 0;
}

void CreateDisjunctGraphs(struct node* my_node, int size) {
int i;

my_node->parent = 1;
my_node->current_node = 1;
my_node->current_node_edges = NULL;
my_node->next = NULL;
for(i = 2; i <= size; ++i) {
my_node->next = (struct node*)malloc(sizeof(struct node));
my_node = my_node->next;
my_node->parent = i;
my_node->current_node = i;
9. Megoldsok 331
Heckl Istvn, PE www.tankonyvtar.hu
my_node->current_node_edges = NULL;
my_node->next = NULL;
}
}
int Where(int recursion, int temp_parent, int u, struct node* actual,
struct node* original) {
struct node* temp;
struct edges* temp_edge;

//az actual a diszjunk grfokbl kpezett listn megy vgig (a
gykerein)
while (actual) {
//ha megtalltuk a keresett cscsot, visszatrsi rtknek
megadjuk, melyik grfba tartozik
if (u == actual->current_node || temp_parent)
return actual->parent;
else {
//ha az adott cscsnak ltezik gyereke, akkor meghvjuk r a
HOLVAN fggvnyt
temp_edge = actual->current_node_edges;
while (temp_edge) {
temp = original;
//megkeressk a segdlistn az adott gyereket
while(temp_edge->current_node != temp->current_node)
temp = temp->next;
temp_parent = Where(1, temp_parent, u, temp, original);
//ha mr megtalltuk a cscsot a grfban, ne nzzk tovbb
a tbbi gyereket is, trjnk vissza a megfelel rtkkel, a rekurzi
miatt
if (temp_parent)
return actual->parent;
temp_edge = temp_edge->next;
}
}
if (recursion)
return 0;
actual = actual->next;
}
return 0;
}
void Union(int size, int destiny, int source, struct node*
my_dijunct_graphs , struct node* original) {
struct node* temp_node, *source_node, *source_node_prev,
*destiny_node;
struct edges* temp_edge;

source_node = my_dijunct_graphs;
destiny_node = my_dijunct_graphs;
//megkeressk, hol van a kt grf gykere, amikre el szeretnnk
vgezni az UNI mveletet
while (source_node->current_node != source) {
source_node_prev = source_node;
source_node = source_node->next;
}
while (destiny_node->current_node != destiny)
destiny_node = destiny_node->next;

//ha a source s a destiny grfok egyms utn vannak a diszjunk
grfokat tartalmaz listban
332 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
//kivesszk a diszjunk grfok listjbl a source elemet
if (destiny_node->next->current_node == source) {
destiny_node->next = source_node->next;
/*destiny_original->mod_next = source_original->next;*/
source_node->next = NULL;
/*source_original->mod_next = NULL;*/
//tlltom a szljt, gy a HOLVAN mvelet visszatrsi rtke
konzisztens lesz
source_node->parent = destiny_node->parent;
//megkeressk a source elemet az eredeti listban is
temp_node = original;
while(temp_node->current_node != source)
temp_node = temp_node->next;
//tlltjuk neki is a szljt
temp_node->parent = destiny_node->parent;

//megnzzk, az adott cscsnak vannak-e szomszdai
//ha mg nincs, megcsiinljuk az elst
if (!destiny_node->current_node_edges) {
destiny_node->current_node_edges = (struct
edges*)malloc(sizeof(struct edges));
destiny_node->current_node_edges->next = NULL;
destiny_node->current_node_edges->current_node = source_node-
>current_node;
//az eredeti listnl is belltjuk a destiny cscs
szomszdait
temp_node = original;
while (temp_node->current_node != destiny_node->current_node)
temp_node = temp_node->next;
temp_node->current_node_edges = destiny_node-
>current_node_edges;
}
//ha van mr szomszd, akkor megkeressk a lncolt lista vgt s
oda szrjuk be az j elemet
else {
temp_edge = destiny_node->current_node_edges;
while (temp_edge->next)
temp_edge = temp_edge->next;
temp_edge->next = (struct edges*)malloc(sizeof(struct edges));
temp_edge = temp_edge->next;
temp_edge->current_node = source;
temp_edge->next = NULL;
}
}
//ha nem egyms utn vannak a listban a sorce s a destiny grfok
else {
source_node_prev->next = source_node->next;
source_node->next = NULL;
source_node->parent = destiny_node->parent;
temp_node = original;
while(temp_node->current_node != source)
temp_node = temp_node->next;
temp_node->parent = destiny_node->parent;
temp_edge = destiny_node->current_node_edges;
if (!destiny_node->current_node_edges) {
destiny_node->current_node_edges = (struct
edges*)malloc(sizeof(struct edges));
destiny_node->current_node_edges->next = NULL;
9. Megoldsok 333
Heckl Istvn, PE www.tankonyvtar.hu
destiny_node->current_node_edges->current_node = source_node-
>current_node;
temp_node = original;
while (temp_node->current_node != destiny_node->current_node)
temp_node = temp_node->next;
temp_node->current_node_edges = destiny_node-
>current_node_edges;
}
else {
temp_edge = destiny_node->current_node_edges;
while (temp_edge->next)
temp_edge = temp_edge->next;
temp_edge->next = (struct edges*)malloc(sizeof(struct edges));
temp_edge = temp_edge->next;
temp_edge->current_node = source;
temp_edge->next = NULL;
}
}
}
void SortByWeight(struct edge_list** root) {
int max;
struct edge_list* temp, *temp_prev, *max_weight, *max_weight_prev;

//elsszr belltjuk, hogy a lista els eleme legyen a legnagyobb
temp_prev = *root;
temp = temp_prev->next;
max_weight = *root;
max_weight_prev = NULL;
max = (*root)->weight;
//vgigmegynk a listn s megkeressnk a tnyleges legnagyobb elemet
while (temp) {
if (temp->weight > max) {
max = temp->weight;
max_weight = temp;
max_weight_prev = temp_prev;
temp_prev = temp;
temp = temp->next;
}
else {
temp_prev = temp;
temp = temp->next;
}
}
//mutatk tlltsa, hogy a legnagyobb elem legyen ell
//ha a lista els eleme a legnagyobb elem, akkor nem kell semmit se
csinlni
if (!max_weight_prev)
;
//ha a msodik a legnagyobb elem
else if (max_weight_prev == (*root)) {
(*root)->next = max_weight->next;
max_weight->next = max_weight_prev;
(*root) = max_weight;
}
//egybknt
else {
max_weight_prev->next = max_weight->next;
max_weight->next = (*root);
(*root) = max_weight;
334 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
}
}
void FreeGraph(struct node* root) {
struct edges* temp_edge1, *temp_edge2;
struct node* temp_node1, *temp_node2;

temp_edge1 = root->current_node_edges;
while (temp_edge1) {
temp_edge2 = temp_edge1;
temp_edge1 = temp_edge1->next;
free(temp_edge2);
}

temp_node1 = root->next;
while (temp_node1) {
temp_edge1 = temp_node1->current_node_edges;
while (temp_edge1) {
temp_edge2 = temp_edge1;
temp_edge1 = temp_edge1->next;
free(temp_edge2);
}
temp_node2 = temp_node1;
temp_node1 = temp_node1->next;
free(temp_node2);
}
}
void FreeGraphList(struct node* root) {
struct node* temp_node1, *temp_node2;

temp_node1 = root->next;
while (temp_node1) {
temp_node2 = temp_node1;
temp_node1 = temp_node1->next;
free(temp_node2);
}
}
void FreeEdgeList(struct edge_list* temp1) {
struct edge_list* temp2;

while(temp1) {
temp2 = temp1;
temp1 = temp1->next;
free(temp2);
}
}
8.1.1.
#include <stdio.h>

void print(double* tomb, int size) {
int idxI;
printf("[");
for (idxI=0; idxI<size; idxI++)
printf("%lf ", tomb[idxI]);
printf("]");

}
int minIndex(double* tomb, int size) {
int minIndex = 0;
9. Megoldsok 335
Heckl Istvn, PE www.tankonyvtar.hu
int idxI;
for (idxI=1; idxI<size; idxI++)
if (tomb[idxI] < tomb[minIndex])
minIndex = idxI;
return minIndex;
}
void swap(double* tomb, int id1, int id2) {
double temp;
temp=tomb[id1];
tomb[id1]=tomb[id2];
tomb[id2]=temp;
}
void minSort(double *tomb, int len) { // complexity: n*n, ascending order
int idxI, c;

for(idxI=0; idxI<len; idxI++) {
c=minIndex(tomb+idxI, len-idxI); // min search at the end of the
array
c=c+idxI;
swap(tomb, c, idxI);
}
}
void boubleSort(double *tomb, int len) { // complexity: n*n, ascending
order
int idxI, idxJ;

for(idxI=0; idxI<len; idxI++) {
for (idxJ=len-1; idxJ>idxI; idxJ--) {
if (tomb[idxJ-1]>tomb[idxJ])
swap(tomb, idxJ-1, idxJ);
}
}
}
int main() {
double myArray[]={22, 16, -7, -42, 6},
myArray2[]={22, 16, -7, -42, 6};
int size = sizeof myArray / sizeof (double); // works only with
static arrays

printf("The original myArray: ");
print(myArray, size);
minSort(myArray, size);
printf("\nThe min sorted myArray: ");
print(myArray, size);

printf("\nThe original myArray: ");
print(myArray2, size);
boubleSort(myArray2, size);
printf("\nThe bubble sorted myArray: ");
print(myArray, size);
return 0;
}
8.1.2.
#include <stdio.h>
void combSort(int *, int);
void insertionSort(int *, int);
int main() {
int idxI;
336 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
int myArray[] = {5,8,3,4,12,45,87};
int myArray2[] = {5,8,3,4,12,45,87};
int size = sizeof(myArray) /sizeof(int);

combSort(myArray2, size);
for (idxI = 0; idxI < size; ++idxI)
printf("%d, ", myArray2[idxI]);
printf("\n");

insertionSort(myArray, size);
for (idxI = 0; idxI < size; ++idxI)
printf("%d, ", myArray[idxI]);
printf("\n");
return 0;
}

void combSort(int * myArray, int size){
int gap = size, idxI, idxJ, swap, temp;
for (;;)
{
gap = (gap *10) /13;
if (gap == 9 || gap == 10)
gap = 11;
if (gap < 1) gap=1;
swap = 0;
for (idxI = 0; idxI < size -gap; idxI++)
{
int idxJ = idxI+gap;
if (myArray[idxI] > myArray[idxJ])
{
temp = myArray[idxI];
myArray[idxI] = myArray[idxJ];
myArray[idxJ] = temp;
swap = 1;
}
}
if (gap == 1 && !swap) break;
}

}
void insertionSort (int * myArray, int size) {
int idxI, idxJ, leftBorder, rightBorder, tempSize, actualElement;

for (idxI = 1; idxI < size; idxI++) {
actualElement = myArray[idxI];
leftBorder = 0;
rightBorder = idxI-1;
while (leftBorder <= rightBorder) {
tempSize = (leftBorder+rightBorder) / 2;
if (actualElement < myArray[tempSize])
rightBorder = tempSize-1;
else
leftBorder = tempSize+1;
}
//mindig egy elemtl balra szrok be, ezrt a tle jobbra lev
elemeket eltolom eggyel
for (idxJ = idxI-1; idxJ >= leftBorder; idxJ--)
myArray[idxJ+1] = myArray[idxJ];
myArray[leftBorder] = actualElement;
9. Megoldsok 337
Heckl Istvn, PE www.tankonyvtar.hu
}
}
8.2.1.
#include <stdio.h>

void print(double* tomb, int size) {
int idxI;
printf("[");
for (idxI=0; idxI<size; idxI++)
printf("%lf ", tomb[idxI]);
printf("]");

}

void swap(double* tomb, int id1, int id2) {
double temp;
temp=tomb[id1];
tomb[id1]=tomb[id2];
tomb[id2]=temp;
}

int partition(double* tomb, int left, int right) { // more clear method:
create a new array and copy values into the begining and ending from the
old one, and copy back the values into the original array
double val=tomb[left];
int lm = left-1; //left margin
int rm = right+1;
while (1) {
do
rm--;
while (tomb[rm] > val);

do
lm++;
while(tomb[lm] < val);

if(lm < rm)
swap(tomb, rm, lm);
else
return rm;
}
return 0; // this point is never reached
}

void quickSort(double* tomb, int left, int right) { // left=first valid
index, right=last valid index
static int level=0;
int idxI;
level++;
for (idxI=0; idxI<level-1; idxI++)
printf("\t");
printf("Begin of quickSort at level %d, [%d, %d]\n", level, left,
right);
if(left < right) {
int split_pt = partition(tomb,left, right);
quickSort(tomb, left, split_pt);
quickSort(tomb, split_pt+1, right);
}
338 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
for (idxI=0; idxI<level-1; idxI++)
printf("\t");
printf("End of quickSort at level %d, [%d, %d]\n", level, left,
right);
level--;
}

int main() {
double myArray[]={0, -6, 7, -42, 6, 9};
int size = sizeof myArray / sizeof (double); // works only with
static arrays

printf("The original myArray: ");
print(myArray, size);
quickSort(myArray, 0, size-1);
printf("\nThe quick sorted myArray: ");
print(myArray, size);
return 0;
}
8.2.2.
#include <stdio.h>
#include <malloc.h>

void fibonacci(long int * fibonacciArray, long int first, long int
second, int count) {
static int level = 0;
long int sum;
int idxI;
if (count) {
level++;
for (idxI = 0; idxI < level - 1; idxI++)
printf("\t");
printf("Begin of Fibonacci series at level %d\n", level);
fibonacciArray[count + idxI + 1] = second + first; //hazugsag, az
utolso szamolas tartalmazza az elozoeket is, igy csak ennek az ertekei
fognak a tombbe irodni
fibonacci(fibonacciArray, second, first + second, count - 1);
for (idxI = 0; idxI < level - 1; idxI++)
printf("\t");
printf("End of Fibonacci series at level %d\n", level);
level--;
}
}

int main() {
int idxI;
int maxIndex;
long int *fibonacciArray;

printf("Max index of the Fibonacci series? ");
scanf("%d", &maxIndex);
if (maxIndex < 3) {
for (idxI = 0; idxI < maxIndex; ++idxI)
printf("%d. element: %d\n", idxI+1, 1);
}
else {
fibonacciArray = (long int *) malloc (sizeof(long int) *
maxIndex);
9. Megoldsok 339
Heckl Istvn, PE www.tankonyvtar.hu
fibonacciArray[0] = fibonacciArray[1] = 1;
for (idxI = 3; idxI <= maxIndex; ++idxI) { //az elemek
meghatarozasa
printf("\n");
fibonacci(fibonacciArray, 1, 1, idxI-2); //alapallapot
}
printf("\n");
for (idxI = 0; idxI < maxIndex; ++idxI) //tagok kiiratasa
printf("%d. element: %ld\n", idxI + 1, fibonacciArray[idxI]);
free(fibonacciArray); //memoriafelszabaditas
}
return 0;
}
8.3.1.
#include <stdio.h>
#include <string.h>
int main() {
int n, idxI, idxJ;
char name[10][30], tempName[30];

printf("Number of names: ");
scanf("%d",&n);
for(idxI = 0; idxI < n; idxI++) {
printf("%d. name:", idxI+1);
scanf("%s", name[idxI]);
}
for(idxI = 0; idxI < n; idxI++)
for(idxJ = 0; idxJ < n; idxJ++) {
if (strcmp(name[idxI], name[idxJ]) < 0) {
strcpy(tempName, name[idxI]);
strcpy(name[idxI], name[idxJ]);
strcpy(name[idxJ], tempName);
}
}
printf("\nThe ordered names are:\n");
for(idxI = 0; idxI < n; idxI++)
printf("%s\n", name[idxI]);
return 0;
}
8.3.2.
#include <stdio.h>
#include <string.h>
int main() {
int numberOfNames, idxI, idxJ;
char name[10][30], prefix[10][30], tempName[30];

printf("Number of names: ");
scanf("%d", &numberOfNames);
for (idxI = 0; idxI < numberOfNames; idxI++) {
printf("%d. prefix: ", idxI + 1);
scanf("%s", prefix[idxI]);
printf("%d. name:", idxI + 1);
scanf("%s", name[idxI]);
}
for (idxI = 0; idxI < numberOfNames; idxI++) {
for (idxJ = 0; idxJ < numberOfNames; idxJ++) {
if (strcmp(name[idxI], name[idxJ]) < 0) {
340 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
strcpy(tempName, name[idxI]);
strcpy(name[idxI], name[idxJ]);
strcpy(name[idxJ], tempName);
strcpy(tempName, prefix[idxI]);
strcpy(prefix[idxI], prefix[idxJ]);
strcpy(prefix[idxJ], tempName);
}
}
}
printf("\nThe ordered names are:\n");
for (idxI = 0; idxI < numberOfNames; idxI++)
printf("%s %s\n", prefix[idxI], name[idxI]);
return 0;
}
8.4.1.
#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct {
int ID;
double size;
char origin[100];
} DataType;

typedef struct le {
DataType* data;
struct le* next;
struct le* prev;
} listElem;

typedef struct {
struct le head; // sentinel
struct le tail; // sentinel
} List;

void displayListElem(DataType* data) {
printf("(ID: %d, ", data->ID);
printf("size: %lf, ", data->size);
printf("origin: %s)", data->origin);
}

void deleteList(List* myList) {
listElem *act;
act = myList->head.next;
if (act == &myList->tail) return; // no list to delete
while (act != &myList->tail) {
act = act->next;
free(act->prev);
}
}

void listList(List* myList) {
listElem *act=myList->head.next;
printf("List elments: ");
while (act != &myList->tail) {
displayListElem(act->data);
act = act->next;
9. Megoldsok 341
Heckl Istvn, PE www.tankonyvtar.hu
if (act != &myList->tail)
printf(", ");
}
printf("\n");
}

void insert(List* myList, DataType* newData) {
listElem *act=myList->head.next, *newElem=NULL, *beforeElem=NULL,
*afterElem=NULL;
while (act != &myList->tail && act->data->ID > newData->ID) {
// beware the order of the conditions are important
// first we have to check if act is a valid element, only then can we
check it's ID field
act = act->next;
}
afterElem = act;
beforeElem = act->prev;
newElem = (listElem*)malloc(sizeof(listElem));
newElem->data = newData;
beforeElem->next = newElem;
newElem->next = afterElem;
afterElem->prev = newElem;
newElem->prev = beforeElem;
}

int main() {
// List myList={{NULL, NULL, NULL}, {NULL, NULL, NULL}};
List myList={NULL}; // do the same as the previous row
myList.head.next = &myList.tail;
myList.tail.prev = &myList.head;
DataType testData[]={{1, 2.3, "Hu"}, {7, 12.3, "Ro"}, {0, 45.3,
"Eu"}, {5, 14.1, "Gb"} };
int idxI;

for (idxI=0; idxI<4; idxI++) {
printf("Insert ");
displayListElem(&testData[idxI]);
printf("\n");
insert(&myList, &testData[idxI]);
listList(&myList);
printf("\n");
}
deleteList(&myList);
return 0;
}
8.4.2.
#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct {
int ID;
double size;
char origin[100];
} DataType;

typedef struct le {
DataType* data;
342 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
struct le* next;
struct le* prev;
} listElem;

typedef struct {
struct le head; // sentinel
struct le tail; // sentinel
int count;
} List;

void displayListElem(DataType* data) {
printf("(ID: %d, ", data->ID);
printf("size: %lf, ", data->size);
printf("origin: %s)", data->origin);
}

void deleteList(List* myList) {
listElem *act;
act = myList->head.next;
if (act == &myList->tail) return; // no list to delete
while (act != &myList->tail) {
act = act->next;
free(act->prev);
}
}

void listList(List* myList) {
listElem *act=myList->head.next;
printf("List elments: ");
while (act != &myList->tail) {
displayListElem(act->data);
act = act->next;
if (act != &myList->tail)
printf(", ");
}
printf("\n");
printf("Element count: %d\n", myList->count);
}

void insert(List* myList, DataType* newData) {
listElem *act=myList->head.next, *newElem=NULL, *beforeElem=NULL,
*afterElem=NULL;
while (act != &myList->tail && act->data->ID > newData->ID) {
// beware the order of the conditions are important
// first we have to check if act is a valid element, only then can we
check it's ID field
act = act->next;
}
afterElem = act;
beforeElem = act->prev;
newElem = (listElem*)malloc(sizeof(listElem));
newElem->data = newData;
beforeElem->next = newElem;
newElem->next = afterElem;
afterElem->prev = newElem;
newElem->prev = beforeElem;
}

int main() {
9. Megoldsok 343
Heckl Istvn, PE www.tankonyvtar.hu
// List myList={{NULL, NULL, NULL}, {NULL, NULL, NULL}};
List myList={NULL}; // do the same as the previous row
myList.count = 0;
myList.head.next = &myList.tail;
myList.tail.prev = &myList.head;
DataType testData[]={{1, 2.3, "Hu"}, {7, 12.3, Ro}, {0, 45.3,
"Eu"}, {5, 14.1, "Gb"} };
int idxI;

for (idxI=0; idxI<4; idxI++) {
printf("Insert ");
displayListElem(&testData[idxI]);
printf("\n");
insert(&myList, &testData[idxI]);
myList.count += 1;
listList(&myList);
printf("\n");
}
printf("Count: %d\n", myList.count);
deleteList(&myList);
return 0;
}
8.5.1.
#include <stdio.h>
#include <malloc.h>
typedef struct {
int ID;
char name[50];
float price;
} headphone;

void exchange(headphone** a, int i, int j) {
headphone *temp=a[i]; // no structure copy
a[i]=a[j];
a[j]=temp;
}

void downheap(headphone** a, int size, int parent) {
int left=2*parent+1, right=2*parent+2, maxChild=left;
if (left>=size) return; // a[v] has no children
// if there are one child then left is the maxChild
if (right<size && a[right]->ID > a[left]->ID) maxChild=right;
// if there are two children and the right is bigger, then it will be
maxChild
if (a[parent]->ID >= a[maxChild]->ID) return; // it is a heap
else {
exchange(a, parent, maxChild); // force heap property at the top
downheap(a, size, maxChild); // force heap property in the changed
subtree
}
}

void buildheap(headphone** a, int n) {
int v;
for (v=n/2-1; v>=0; v--)
downheap(a, n, v);
}

344 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
void heapsort(headphone** a, int n) {
buildheap(a, n);
while (n>1) {
n--;
exchange(a, 0, n);
// put the biggest of the current heap into its final place in the
array
// put the most right leaf at the top of the heap
downheap(a, n, 0);
// force the heap property on the decrease heap
}
}

void printHeadphone(headphone* node) {
if (!node) return;
printf("[ID: %3d, ", node->ID);
printf("name: %10s, ", node->name);
printf("price: %6.2f]", node->price);
}

void printArray(headphone** array, int size) {
int idxI=0;
for (;idxI<size;idxI++) {
printHeadphone(array[idxI]);
printf("\n");
}
}

int main() {
headphone b={23, "Genius", 2710}, c={7, "MS", 3250},
d={63, "Verano", 1160}, e={11, "LG", 6980}, f={9, "Samsung", 2370},
g={42, "Ele", 1260}, h={12, "Azona", 1230};
headphone* a[]={&b, &c, &d, &e, &f, &g, &h};
int size = sizeof (a) / sizeof(headphone*);

printf("Unordered heap:\n");
printArray(a, size);
heapsort(a, size);
printf("\nOrdered heap:\n");
printArray(a, size);
return 0;
}
8.6.1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFAULT_INPUTFILE "words.txt"
#define MAX_LENGTH 16
#define TRUE 1
#define FALSE 0

typedef char TWord[MAX_LENGTH];

// A > B
int Greater(char * A, char * B)
{
int i;
9. Megoldsok 345
Heckl Istvn, PE www.tankonyvtar.hu
int sa = strlen(A);
int sb = strlen(B);
int min = sa < sb ? sa : sb;
for (i = 0; i < min; i++)
{
if (A[i] > B[i])
return TRUE;
if (A[i] < B[i])
return FALSE;
}
return sa > sb;
}

int ReadWords(FILE * fd, TWord ** W)
{
int num, i;
fscanf(fd, "%d", &num);
(*W) = (TWord *)malloc(sizeof(TWord) * num);
for (i = 0; i < num; i++)
fscanf(fd, "%s", (*W)[i]);
return num;
}

void PrintWords(TWord * W, int num)
{
int i;
for (i = 0; i < num; i++)
printf("\t%d.: %s\n", i + 1, W[i]);
}

void Sort(TWord * W, int num)
{
int min, i, j;
TWord Temp;
for (i = 0; i < num - 1; i++)
{
min = i;
for (j = i; j < num; j++)
{
if (Greater(W[min], W[j]))
min = j;
}
strcpy(Temp, W[min]);
strcpy(W[min], W[i]);
strcpy(W[i], Temp);
}
}

int main(int argc, char * argv[])
{
TWord * Words;
int WNum;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
perror(Error);
return 0;
}
WNum = ReadWords(fd, &Words);
346 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
fclose(fd);
printf("Read words:\n");
PrintWords(Words, WNum);
Sort(Words, WNum);
printf("\n***************\nSorted words:\n");
PrintWords(Words, WNum);
free(Words);
Words = NULL;
return 0;
}

// words.txt
7
WARIOR
APPLE
SZOKOZSHIP
BOOK
SZOKOZ
PHISIC
LIMON
8.7.1.
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define DEFAULT_INPUTFILE "memo1.txt"
#define MAX_MEMO_LEN 21
#define TRUE 1
#define FALSE (!TRUE)

struct TMemo
{
int Year;
int Month;
int Day;
int Hour;
char m[MAX_MEMO_LEN];
};

int ReadMemos(FILE * fd, struct TMemo ** M)
{
int c, i;
struct TMemo * mptr;
fscanf(fd, "%d", &c);
(*M) = mptr = (struct TMemo*)malloc(sizeof(struct TMemo) * c);
for (i = 0; i < c; i++)
{
fscanf(fd,"%d %d %d %d", &mptr->Year, &mptr->Month, &mptr->Day,
&mptr->Hour);
fscanf(fd, "%s", mptr->m);
mptr++;
}
return c;
}

void PrintMemos(struct TMemo * M, int c)
{
int i;
9. Megoldsok 347
Heckl Istvn, PE www.tankonyvtar.hu
for (i = 0; i < c; i++)
{
printf("Year: %d\nMonth: %d\nDay: %d\nHour: %d\n\t %s\n\n", M->Year,
M->Month, M->Day, M->Hour, M->m);
M++;
}
}

// A > B
int Greater(struct TMemo * A, struct TMemo * B)
{
if (A->Year != B->Year)
{
return (A->Year > B->Year);
} else
{
if (A->Month != B->Month)
{
return (A->Month > B->Month);
} else
{
if (A->Day != B->Day)
{
return (A->Day > B->Day);
} else
{
if (A->Hour > B->Hour)
return (A->Hour > B->Hour);
}
}
}
return FALSE;
}

void Sort(struct TMemo * M, int c)
{
int i, j, mini;
struct TMemo tmp;
for (i = 0; i < c - 1; i++)
{
mini = i;
for (j = i; j < c; j++)
{
if (Greater( M + mini, M + j))
mini = j;
}
memcpy(&tmp, M + mini, sizeof(struct TMemo));
memcpy(M + mini, M + i, sizeof(struct TMemo));
memcpy(M + i, &tmp, sizeof(struct TMemo));
}
}

int main(int argc, char * argv[])
{
struct TMemo * Memos;
int MCount = 0;
FILE * fd = fopen(argc > 1 ? argv[1] : DEFAULT_INPUTFILE, "r");
if (fd == NULL)
{
348 Adatstruktrk s algoritmusok pldatr
www.tankonyvtar.hu Heckl Istvn, PE
perror("Error");
return 0;
}
MCount = ReadMemos(fd, &Memos);
fclose(fd);
Sort(Memos, MCount);
PrintMemos(Memos, MCount);
free(Memos);
Memos = NULL;
return 0;
}